* Add autopromote condition APCOND_BLOCKED to autopromote blocked users to various...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 /**@}}*/
44
45 /**
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
49 */
50 public function __construct( Title $title, $oldId = null ) {
51 $this->mTitle =& $title;
52 $this->mOldId = $oldId;
53 }
54
55 /**
56 * Constructor from an article article
57 * @param $id The article ID to load
58 */
59 public static function newFromID( $id ) {
60 $t = Title::newFromID( $id );
61 return $t == null ? null : new Article( $t );
62 }
63
64 /**
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
68 */
69 public function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom = $from;
71 }
72
73 /**
74 * If this page is a redirect, get its target
75 *
76 * The target will be fetched from the redirect table if possible.
77 * If this page doesn't have an entry there, call insertRedirect()
78 * @return mixed Title object, or null if this page is not a redirect
79 */
80 public function getRedirectTarget() {
81 if( !$this->mTitle || !$this->mTitle->isRedirect() )
82 return null;
83 if( !is_null($this->mRedirectTarget) )
84 return $this->mRedirectTarget;
85 # Query the redirect table
86 $dbr = wfGetDB( DB_SLAVE );
87 $row = $dbr->selectRow( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID() ),
90 __METHOD__
91 );
92 if( $row ) {
93 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
94 }
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget = $this->insertRedirect();
97 }
98
99 /**
100 * Insert an entry for this page into the redirect table.
101 *
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object
104 */
105 public function insertRedirect() {
106 $retval = Title::newFromRedirect( $this->getContent() );
107 if( !$retval ) {
108 return null;
109 }
110 $dbw = wfGetDB( DB_MASTER );
111 $dbw->replace( 'redirect', array('rd_from'),
112 array(
113 'rd_from' => $this->getID(),
114 'rd_namespace' => $retval->getNamespace(),
115 'rd_title' => $retval->getDBkey()
116 ),
117 __METHOD__
118 );
119 return $retval;
120 }
121
122 /**
123 * Get the Title object this page redirects to
124 *
125 * @return mixed false, Title of in-wiki target, or string with URL
126 */
127 public function followRedirect() {
128 $text = $this->getContent();
129 return $this->followRedirectText( $text );
130 }
131
132 /**
133 * Get the Title object this text redirects to
134 *
135 * @return mixed false, Title of in-wiki target, or string with URL
136 */
137 public function followRedirectText( $text ) {
138 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
139 # process if title object is valid and not special:userlogout
140 if( $rt ) {
141 if( $rt->getInterwiki() != '' ) {
142 if( $rt->isLocal() ) {
143 // Offsite wikis need an HTTP redirect.
144 //
145 // This can be hard to reverse and may produce loops,
146 // so they may be disabled in the site configuration.
147 $source = $this->mTitle->getFullURL( 'redirect=no' );
148 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
149 }
150 } else {
151 if( $rt->getNamespace() == NS_SPECIAL ) {
152 // Gotta handle redirects to special pages differently:
153 // Fill the HTTP response "Location" header and ignore
154 // the rest of the page we're on.
155 //
156 // This can be hard to reverse, so they may be disabled.
157 if( $rt->isSpecial( 'Userlogout' ) ) {
158 // rolleyes
159 } else {
160 return $rt->getFullURL();
161 }
162 }
163 return $rt;
164 }
165 }
166 // No or invalid redirect
167 return false;
168 }
169
170 /**
171 * get the title object of the article
172 */
173 public function getTitle() {
174 return $this->mTitle;
175 }
176
177 /**
178 * Clear the object
179 * @private
180 */
181 public function clear() {
182 $this->mDataLoaded = false;
183 $this->mContentLoaded = false;
184
185 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
186 $this->mRedirectedFrom = null; # Title object if set
187 $this->mRedirectTarget = null; # Title object if set
188 $this->mUserText =
189 $this->mTimestamp = $this->mComment = '';
190 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
191 $this->mTouched = '19700101000000';
192 $this->mForUpdate = false;
193 $this->mIsRedirect = false;
194 $this->mRevIdFetched = 0;
195 $this->mRedirectUrl = false;
196 $this->mLatest = false;
197 $this->mPreparedEdit = false;
198 }
199
200 /**
201 * Note that getContent/loadContent do not follow redirects anymore.
202 * If you need to fetch redirectable content easily, try
203 * the shortcut in Article::followContent()
204 *
205 * @return Return the text of this revision
206 */
207 public function getContent() {
208 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
209 wfProfileIn( __METHOD__ );
210 if( $this->getID() === 0 ) {
211 # If this is a MediaWiki:x message, then load the messages
212 # and return the message value for x.
213 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
214 # If this is a system message, get the default text.
215 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
216 $wgMessageCache->loadAllMessages( $lang );
217 $text = wfMsgGetKey( $message, false, $lang, false );
218 if( wfEmptyMsg( $message, $text ) )
219 $text = '';
220 } else {
221 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
222 }
223 wfProfileOut( __METHOD__ );
224 return $text;
225 } else {
226 $this->loadContent();
227 wfProfileOut( __METHOD__ );
228 return $this->mContent;
229 }
230 }
231
232 /**
233 * Get the text of the current revision. No side-effects...
234 *
235 * @return Return the text of the current revision
236 */
237 public function getRawText() {
238 // Check process cache for current revision
239 if( $this->mContentLoaded && $this->mOldId == 0 ) {
240 return $this->mContent;
241 }
242 $rev = Revision::newFromTitle( $this->mTitle );
243 $text = $rev ? $rev->getRawText() : false;
244 return $text;
245 }
246
247 /**
248 * This function returns the text of a section, specified by a number ($section).
249 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
250 * the first section before any such heading (section 0).
251 *
252 * If a section contains subsections, these are also returned.
253 *
254 * @param $text String: text to look in
255 * @param $section Integer: section number
256 * @return string text of the requested section
257 * @deprecated
258 */
259 public function getSection( $text, $section ) {
260 global $wgParser;
261 return $wgParser->getSection( $text, $section );
262 }
263
264 /**
265 * Get the text that needs to be saved in order to undo all revisions
266 * between $undo and $undoafter. Revisions must belong to the same page,
267 * must exist and must not be deleted
268 * @param $undo Revision
269 * @param $undoafter Revision Must be an earlier revision than $undo
270 * @return mixed string on success, false on failure
271 */
272 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
273 $undo_text = $undo->getText();
274 $undoafter_text = $undoafter->getText();
275 $cur_text = $this->getContent();
276 if ( $cur_text == $undo_text ) {
277 # No use doing a merge if it's just a straight revert.
278 return $undoafter_text;
279 }
280 $undone_text = '';
281 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
282 return false;
283 return $undone_text;
284 }
285
286 /**
287 * @return int The oldid of the article that is to be shown, 0 for the
288 * current revision
289 */
290 public function getOldID() {
291 if( is_null( $this->mOldId ) ) {
292 $this->mOldId = $this->getOldIDFromRequest();
293 }
294 return $this->mOldId;
295 }
296
297 /**
298 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
299 *
300 * @return int The old id for the request
301 */
302 public function getOldIDFromRequest() {
303 global $wgRequest;
304 $this->mRedirectUrl = false;
305 $oldid = $wgRequest->getVal( 'oldid' );
306 if( isset( $oldid ) ) {
307 $oldid = intval( $oldid );
308 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
309 $nextid = $this->mTitle->getNextRevisionID( $oldid );
310 if( $nextid ) {
311 $oldid = $nextid;
312 } else {
313 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
314 }
315 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
316 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
317 if( $previd ) {
318 $oldid = $previd;
319 }
320 }
321 }
322 if( !$oldid ) {
323 $oldid = 0;
324 }
325 return $oldid;
326 }
327
328 /**
329 * Load the revision (including text) into this object
330 */
331 function loadContent() {
332 if( $this->mContentLoaded ) return;
333 wfProfileIn( __METHOD__ );
334 # Query variables :P
335 $oldid = $this->getOldID();
336 # Pre-fill content with error message so that if something
337 # fails we'll have something telling us what we intended.
338 $this->mOldId = $oldid;
339 $this->fetchContent( $oldid );
340 wfProfileOut( __METHOD__ );
341 }
342
343
344 /**
345 * Fetch a page record with the given conditions
346 * @param $dbr Database object
347 * @param $conditions Array
348 */
349 protected function pageData( $dbr, $conditions ) {
350 $fields = array(
351 'page_id',
352 'page_namespace',
353 'page_title',
354 'page_restrictions',
355 'page_counter',
356 'page_is_redirect',
357 'page_is_new',
358 'page_random',
359 'page_touched',
360 'page_latest',
361 'page_len',
362 );
363 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
364 $row = $dbr->selectRow(
365 'page',
366 $fields,
367 $conditions,
368 __METHOD__
369 );
370 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
371 return $row ;
372 }
373
374 /**
375 * @param $dbr Database object
376 * @param $title Title object
377 */
378 public function pageDataFromTitle( $dbr, $title ) {
379 return $this->pageData( $dbr, array(
380 'page_namespace' => $title->getNamespace(),
381 'page_title' => $title->getDBkey() ) );
382 }
383
384 /**
385 * @param $dbr Database
386 * @param $id Integer
387 */
388 protected function pageDataFromId( $dbr, $id ) {
389 return $this->pageData( $dbr, array( 'page_id' => $id ) );
390 }
391
392 /**
393 * Set the general counter, title etc data loaded from
394 * some source.
395 *
396 * @param $data Database row object or "fromdb"
397 */
398 public function loadPageData( $data = 'fromdb' ) {
399 if( $data === 'fromdb' ) {
400 $dbr = wfGetDB( DB_MASTER );
401 $data = $this->pageDataFromId( $dbr, $this->getId() );
402 }
403
404 $lc = LinkCache::singleton();
405 if( $data ) {
406 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
407
408 $this->mTitle->mArticleID = $data->page_id;
409
410 # Old-fashioned restrictions
411 $this->mTitle->loadRestrictions( $data->page_restrictions );
412
413 $this->mCounter = $data->page_counter;
414 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
415 $this->mIsRedirect = $data->page_is_redirect;
416 $this->mLatest = $data->page_latest;
417 } else {
418 if( is_object( $this->mTitle ) ) {
419 $lc->addBadLinkObj( $this->mTitle );
420 }
421 $this->mTitle->mArticleID = 0;
422 }
423
424 $this->mDataLoaded = true;
425 }
426
427 /**
428 * Get text of an article from database
429 * Does *NOT* follow redirects.
430 * @param $oldid Int: 0 for whatever the latest revision is
431 * @return string
432 */
433 function fetchContent( $oldid = 0 ) {
434 if( $this->mContentLoaded ) {
435 return $this->mContent;
436 }
437
438 $dbr = wfGetDB( DB_MASTER );
439
440 # Pre-fill content with error message so that if something
441 # fails we'll have something telling us what we intended.
442 $t = $this->mTitle->getPrefixedText();
443 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
444 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
445
446 if( $oldid ) {
447 $revision = Revision::newFromId( $oldid );
448 if( is_null( $revision ) ) {
449 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
450 return false;
451 }
452 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
453 if( !$data ) {
454 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
455 return false;
456 }
457 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
458 $this->loadPageData( $data );
459 } else {
460 if( !$this->mDataLoaded ) {
461 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
462 if( !$data ) {
463 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
464 return false;
465 }
466 $this->loadPageData( $data );
467 }
468 $revision = Revision::newFromId( $this->mLatest );
469 if( is_null( $revision ) ) {
470 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
471 return false;
472 }
473 }
474
475 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
476 // We should instead work with the Revision object when we need it...
477 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
478
479 $this->mUser = $revision->getUser();
480 $this->mUserText = $revision->getUserText();
481 $this->mComment = $revision->getComment();
482 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
483
484 $this->mRevIdFetched = $revision->getId();
485 $this->mContentLoaded = true;
486 $this->mRevision =& $revision;
487
488 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
489
490 return $this->mContent;
491 }
492
493 /**
494 * Read/write accessor to select FOR UPDATE
495 *
496 * @param $x Mixed: FIXME
497 */
498 public function forUpdate( $x = NULL ) {
499 return wfSetVar( $this->mForUpdate, $x );
500 }
501
502 /**
503 * Get the database which should be used for reads
504 *
505 * @return Database
506 * @deprecated - just call wfGetDB( DB_MASTER ) instead
507 */
508 function getDB() {
509 wfDeprecated( __METHOD__ );
510 return wfGetDB( DB_MASTER );
511 }
512
513 /**
514 * Get options for all SELECT statements
515 *
516 * @param $options Array: an optional options array which'll be appended to
517 * the default
518 * @return Array: options
519 */
520 protected function getSelectOptions( $options = '' ) {
521 if( $this->mForUpdate ) {
522 if( is_array( $options ) ) {
523 $options[] = 'FOR UPDATE';
524 } else {
525 $options = 'FOR UPDATE';
526 }
527 }
528 return $options;
529 }
530
531 /**
532 * @return int Page ID
533 */
534 public function getID() {
535 if( $this->mTitle ) {
536 return $this->mTitle->getArticleID();
537 } else {
538 return 0;
539 }
540 }
541
542 /**
543 * @return bool Whether or not the page exists in the database
544 */
545 public function exists() {
546 return $this->getId() > 0;
547 }
548
549 /**
550 * Check if this page is something we're going to be showing
551 * some sort of sensible content for. If we return false, page
552 * views (plain action=view) will return an HTTP 404 response,
553 * so spiders and robots can know they're following a bad link.
554 *
555 * @return bool
556 */
557 public function hasViewableContent() {
558 return $this->exists() || $this->mTitle->isAlwaysKnown();
559 }
560
561 /**
562 * @return int The view count for the page
563 */
564 public function getCount() {
565 if( -1 == $this->mCounter ) {
566 $id = $this->getID();
567 if( $id == 0 ) {
568 $this->mCounter = 0;
569 } else {
570 $dbr = wfGetDB( DB_SLAVE );
571 $this->mCounter = $dbr->selectField( 'page',
572 'page_counter',
573 array( 'page_id' => $id ),
574 __METHOD__,
575 $this->getSelectOptions()
576 );
577 }
578 }
579 return $this->mCounter;
580 }
581
582 /**
583 * Determine whether a page would be suitable for being counted as an
584 * article in the site_stats table based on the title & its content
585 *
586 * @param $text String: text to analyze
587 * @return bool
588 */
589 public function isCountable( $text ) {
590 global $wgUseCommaCount;
591
592 $token = $wgUseCommaCount ? ',' : '[[';
593 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
594 }
595
596 /**
597 * Tests if the article text represents a redirect
598 *
599 * @param $text String: FIXME
600 * @return bool
601 */
602 public function isRedirect( $text = false ) {
603 if( $text === false ) {
604 if( $this->mDataLoaded ) {
605 return $this->mIsRedirect;
606 }
607 // Apparently loadPageData was never called
608 $this->loadContent();
609 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
610 } else {
611 $titleObj = Title::newFromRedirect( $text );
612 }
613 return $titleObj !== NULL;
614 }
615
616 /**
617 * Returns true if the currently-referenced revision is the current edit
618 * to this page (and it exists).
619 * @return bool
620 */
621 public function isCurrent() {
622 # If no oldid, this is the current version.
623 if( $this->getOldID() == 0 ) {
624 return true;
625 }
626 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
627 }
628
629 /**
630 * Loads everything except the text
631 * This isn't necessary for all uses, so it's only done if needed.
632 */
633 protected function loadLastEdit() {
634 if( -1 != $this->mUser )
635 return;
636
637 # New or non-existent articles have no user information
638 $id = $this->getID();
639 if( 0 == $id ) return;
640
641 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
642 if( !is_null( $this->mLastRevision ) ) {
643 $this->mUser = $this->mLastRevision->getUser();
644 $this->mUserText = $this->mLastRevision->getUserText();
645 $this->mTimestamp = $this->mLastRevision->getTimestamp();
646 $this->mComment = $this->mLastRevision->getComment();
647 $this->mMinorEdit = $this->mLastRevision->isMinor();
648 $this->mRevIdFetched = $this->mLastRevision->getId();
649 }
650 }
651
652 public function getTimestamp() {
653 // Check if the field has been filled by ParserCache::get()
654 if( !$this->mTimestamp ) {
655 $this->loadLastEdit();
656 }
657 return wfTimestamp(TS_MW, $this->mTimestamp);
658 }
659
660 public function getUser() {
661 $this->loadLastEdit();
662 return $this->mUser;
663 }
664
665 public function getUserText() {
666 $this->loadLastEdit();
667 return $this->mUserText;
668 }
669
670 public function getComment() {
671 $this->loadLastEdit();
672 return $this->mComment;
673 }
674
675 public function getMinorEdit() {
676 $this->loadLastEdit();
677 return $this->mMinorEdit;
678 }
679
680 /* Use this to fetch the rev ID used on page views */
681 public function getRevIdFetched() {
682 $this->loadLastEdit();
683 return $this->mRevIdFetched;
684 }
685
686 /**
687 * @param $limit Integer: default 0.
688 * @param $offset Integer: default 0.
689 */
690 public function getContributors($limit = 0, $offset = 0) {
691 # XXX: this is expensive; cache this info somewhere.
692
693 $contribs = array();
694 $dbr = wfGetDB( DB_SLAVE );
695 $revTable = $dbr->tableName( 'revision' );
696 $userTable = $dbr->tableName( 'user' );
697 $user = $this->getUser();
698 $pageId = $this->getId();
699
700 $deletedBit = $dbr->bitAnd('rev_deleted', Revision::DELETED_USER); // username hidden?
701
702 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
703 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
704 WHERE rev_page = $pageId
705 AND rev_user != $user
706 AND $deletedBit = 0
707 GROUP BY rev_user, rev_user_text, user_real_name
708 ORDER BY timestamp DESC";
709
710 if($limit > 0)
711 $sql = $dbr->limitResult($sql, $limit, $offset);
712
713 $sql .= ' '. $this->getSelectOptions();
714
715 $res = $dbr->query($sql, __METHOD__ );
716
717 return new UserArrayFromResult( $res );
718 }
719
720 /**
721 * This is the default action of the script: just view the page of
722 * the given title.
723 */
724 public function view() {
725 global $wgUser, $wgOut, $wgRequest, $wgContLang;
726 global $wgEnableParserCache, $wgStylePath, $wgParser;
727 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
728 global $wgDefaultRobotPolicy;
729
730 # Let the parser know if this is the printable version
731 if( $wgOut->isPrintable() ) {
732 $wgOut->parserOptions()->setIsPrintable( true );
733 }
734
735 wfProfileIn( __METHOD__ );
736
737 # Get variables from query string
738 $oldid = $this->getOldID();
739
740 # Try client and file cache
741 if( $oldid === 0 && $this->checkTouched() ) {
742 global $wgUseETag;
743 if( $wgUseETag ) {
744 $parserCache = ParserCache::singleton();
745 $wgOut->setETag( $parserCache->getETag($this, $wgOut->parserOptions()) );
746 }
747 # Is is client cached?
748 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
749 wfProfileOut( __METHOD__ );
750 return;
751 # Try file cache
752 } else if( $this->tryFileCache() ) {
753 # tell wgOut that output is taken care of
754 $wgOut->disable();
755 $this->viewUpdates();
756 wfProfileOut( __METHOD__ );
757 return;
758 }
759 }
760
761 $ns = $this->mTitle->getNamespace(); # shortcut
762 $sk = $wgUser->getSkin();
763
764 # getOldID may want us to redirect somewhere else
765 if( $this->mRedirectUrl ) {
766 $wgOut->redirect( $this->mRedirectUrl );
767 wfProfileOut( __METHOD__ );
768 return;
769 }
770
771 $diff = $wgRequest->getVal( 'diff' );
772 $rcid = $wgRequest->getVal( 'rcid' );
773 $rdfrom = $wgRequest->getVal( 'rdfrom' );
774 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
775 $purge = $wgRequest->getVal( 'action' ) == 'purge';
776 $return404 = false;
777
778 $wgOut->setArticleFlag( true );
779
780 # Discourage indexing of printable versions, but encourage following
781 if( $wgOut->isPrintable() ) {
782 $policy = 'noindex,follow';
783 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
784 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
785 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
786 # Honour customised robot policies for this namespace
787 $policy = $wgNamespaceRobotPolicies[$ns];
788 } else {
789 $policy = $wgDefaultRobotPolicy;
790 }
791 $wgOut->setRobotPolicy( $policy );
792
793 # Allow admins to see deleted content if explicitly requested
794 $delId = $diff ? $diff : $oldid;
795 $unhide = $wgRequest->getInt('unhide') == 1;
796 # If we got diff and oldid in the query, we want to see a
797 # diff page instead of the article.
798 if( !is_null( $diff ) ) {
799 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
800
801 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
802 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
803 // DifferenceEngine directly fetched the revision:
804 $this->mRevIdFetched = $de->mNewid;
805 $de->showDiffPage( $diffOnly );
806
807 // Needed to get the page's current revision
808 $this->loadPageData();
809 if( $diff == 0 || $diff == $this->mLatest ) {
810 # Run view updates for current revision only
811 $this->viewUpdates();
812 }
813 wfProfileOut( __METHOD__ );
814 return;
815 }
816
817 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
818 # User/User_talk subpages are not modified. (bug 11443)
819 if( !$this->mTitle->isSubpage() ) {
820 $block = new Block();
821 if( $block->load( $this->mTitle->getBaseText() ) ) {
822 $wgOut->setRobotpolicy( 'noindex,nofollow' );
823 }
824 }
825 }
826
827 # Should the parser cache be used?
828 $pcache = $this->useParserCache( $oldid );
829 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
830 if( $wgUser->getOption( 'stubthreshold' ) ) {
831 wfIncrStats( 'pcache_miss_stub' );
832 }
833
834 $wasRedirected = false;
835 if( isset( $this->mRedirectedFrom ) ) {
836 // This is an internally redirected page view.
837 // We'll need a backlink to the source page for navigation.
838 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
839 $redir = $sk->link(
840 $this->mRedirectedFrom,
841 null,
842 array(),
843 array( 'redirect' => 'no' ),
844 array( 'known', 'noclasses' )
845 );
846 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
847 $wgOut->setSubtitle( $s );
848
849 // Set the fragment if one was specified in the redirect
850 if( strval( $this->mTitle->getFragment() ) != '' ) {
851 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
852 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
853 }
854
855 // Add a <link rel="canonical"> tag
856 $wgOut->addLink( array( 'rel' => 'canonical',
857 'href' => $this->mTitle->getLocalURL() )
858 );
859 $wasRedirected = true;
860 }
861 } elseif( !empty( $rdfrom ) ) {
862 // This is an externally redirected view, from some other wiki.
863 // If it was reported from a trusted site, supply a backlink.
864 global $wgRedirectSources;
865 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
866 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
867 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
868 $wgOut->setSubtitle( $s );
869 $wasRedirected = true;
870 }
871 }
872
873 # Allow a specific header on talk pages, like [[MediaWiki:Talkpagetext]]
874 if( $this->mTitle->isTalkPage() ) {
875 $msg = wfMsgNoTrans( 'talkpageheader' );
876 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
877 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
878 }
879 }
880
881 $outputDone = false;
882 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
883 if( $pcache && $wgOut->tryParserCache( $this ) ) {
884 // Ensure that UI elements requiring revision ID have
885 // the correct version information.
886 $wgOut->setRevisionId( $this->mLatest );
887 $outputDone = true;
888 }
889 # Fetch content and check for errors
890 if( !$outputDone ) {
891 # If the article does not exist and was deleted/moved, show the log
892 if( $this->getID() == 0 ) {
893 $this->showLogs();
894 }
895 $text = $this->getContent();
896 // For now, check also for ID until getContent actually returns
897 // false for pages that do not exists
898 if( $text === false || $this->getID() === 0 ) {
899 # Failed to load, replace text with error message
900 $t = $this->mTitle->getPrefixedText();
901 if( $oldid ) {
902 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
903 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
904 // Always use page content for pages in the MediaWiki namespace
905 // since it contains the default message
906 } elseif ( $this->mTitle->getNamespace() != NS_MEDIAWIKI ) {
907 $text = wfMsgExt( 'noarticletext', 'parsemag' );
908 }
909 }
910
911 # Non-existent pages
912 if( $this->getID() === 0 ) {
913 $wgOut->setRobotPolicy( 'noindex,nofollow' );
914 $text = "<div class='noarticletext'>\n$text\n</div>";
915 if( !$this->hasViewableContent() ) {
916 // If there's no backing content, send a 404 Not Found
917 // for better machine handling of broken links.
918 $return404 = true;
919 }
920 }
921
922 if( $return404 ) {
923 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
924 }
925
926 # Another whitelist check in case oldid is altering the title
927 if( !$this->mTitle->userCanRead() ) {
928 $wgOut->loginToUse();
929 $wgOut->output();
930 $wgOut->disable();
931 wfProfileOut( __METHOD__ );
932 return;
933 }
934
935 # For ?curid=x urls, disallow indexing
936 if( $wgRequest->getInt('curid') )
937 $wgOut->setRobotPolicy( 'noindex,follow' );
938
939 # We're looking at an old revision
940 if( !empty( $oldid ) ) {
941 $wgOut->setRobotPolicy( 'noindex,nofollow' );
942 if( is_null( $this->mRevision ) ) {
943 // FIXME: This would be a nice place to load the 'no such page' text.
944 } else {
945 $this->setOldSubtitle( $oldid );
946 # Allow admins to see deleted content if explicitly requested
947 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
948 // If the user is not allowed to see it...
949 if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
950 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
951 'rev-deleted-text-permission' );
952 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
953 wfProfileOut( __METHOD__ );
954 return;
955 // If the user needs to confirm that they want to see it...
956 } else if( !$unhide ) {
957 # Give explanation and add a link to view the revision...
958 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
959 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
960 array('rev-deleted-text-unhide',$link) );
961 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
962 wfProfileOut( __METHOD__ );
963 return;
964 // We are allowed to see...
965 } else {
966 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
967 'rev-deleted-text-view' );
968 }
969 }
970 // Is this the current revision and otherwise cacheable? Try the parser cache...
971 if( $oldid === $this->getLatest() && $this->useParserCache( false )
972 && $wgOut->tryParserCache( $this ) )
973 {
974 $outputDone = true;
975 }
976 }
977 }
978
979 // Ensure that UI elements requiring revision ID have
980 // the correct version information.
981 $wgOut->setRevisionId( $this->getRevIdFetched() );
982
983 if( $outputDone ) {
984 // do nothing...
985 // Pages containing custom CSS or JavaScript get special treatment
986 } else if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
987 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
988 // Give hooks a chance to customise the output
989 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
990 // Wrap the whole lot in a <pre> and don't parse
991 $m = array();
992 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
993 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
994 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
995 $wgOut->addHTML( "\n</pre>\n" );
996 }
997 } else if( $rt = Title::newFromRedirectArray( $text ) ) { # get an array of redirect targets
998 # Don't append the subtitle if this was an old revision
999 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1000 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
1001 $wgOut->addParserOutputNoText( $parseout );
1002 } else if( $pcache ) {
1003 # Display content and save to parser cache
1004 $this->outputWikiText( $text );
1005 } else {
1006 # Display content, don't attempt to save to parser cache
1007 # Don't show section-edit links on old revisions... this way lies madness.
1008 if( !$this->isCurrent() ) {
1009 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
1010 }
1011 # Display content and don't save to parser cache
1012 # With timing hack -- TS 2006-07-26
1013 $time = -wfTime();
1014 $this->outputWikiText( $text, false );
1015 $time += wfTime();
1016
1017 # Timing hack
1018 if( $time > 3 ) {
1019 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
1020 $this->mTitle->getPrefixedDBkey()));
1021 }
1022
1023 if( !$this->isCurrent() ) {
1024 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
1025 }
1026 }
1027 }
1028 /* title may have been set from the cache */
1029 $t = $wgOut->getPageTitle();
1030 if( empty( $t ) ) {
1031 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1032
1033 # For the main page, overwrite the <title> element with the con-
1034 # tents of 'pagetitle-view-mainpage' instead of the default (if
1035 # that's not empty).
1036 if( $this->mTitle->equals( Title::newMainPage() ) &&
1037 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
1038 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
1039 }
1040 }
1041
1042 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1043 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1044 $wgOut->addWikiMsg('anontalkpagetext');
1045 }
1046
1047 # If we have been passed an &rcid= parameter, we want to give the user a
1048 # chance to mark this new article as patrolled.
1049 if( !empty( $rcid ) && $this->mTitle->exists() && $this->mTitle->quickUserCan( 'patrol' ) ) {
1050 $wgOut->addHTML(
1051 "<div class='patrollink'>" .
1052 wfMsgHtml(
1053 'markaspatrolledlink',
1054 $sk->link(
1055 $this->mTitle,
1056 wfMsgHtml( 'markaspatrolledtext' ),
1057 array(),
1058 array(
1059 'action' => 'markpatrolled',
1060 'rcid' => $rcid
1061 ),
1062 array( 'known', 'noclasses' )
1063 )
1064 ) .
1065 '</div>'
1066 );
1067 }
1068
1069 # Trackbacks
1070 if( $wgUseTrackbacks ) {
1071 $this->addTrackbacks();
1072 }
1073
1074 $this->viewUpdates();
1075 wfProfileOut( __METHOD__ );
1076 }
1077
1078 protected function showLogs() {
1079 global $wgUser, $wgOut;
1080 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1081 $pager = new LogPager( $loglist, array('move', 'delete'), false,
1082 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
1083 if( $pager->getNumRows() > 0 ) {
1084 $pager->mLimit = 10;
1085 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1086 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1087 $wgOut->addHTML(
1088 $loglist->beginLogEventsList() .
1089 $pager->getBody() .
1090 $loglist->endLogEventsList()
1091 );
1092 if( $pager->getNumRows() > 10 ) {
1093 $wgOut->addHTML( $wgUser->getSkin()->link(
1094 SpecialPage::getTitleFor( 'Log' ),
1095 wfMsgHtml( 'log-fulllog' ),
1096 array(),
1097 array( 'page' => $this->mTitle->getPrefixedText() )
1098 ) );
1099 }
1100 $wgOut->addHTML( '</div>' );
1101 }
1102 }
1103
1104 /*
1105 * Should the parser cache be used?
1106 */
1107 protected function useParserCache( $oldid ) {
1108 global $wgUser, $wgEnableParserCache;
1109
1110 return $wgEnableParserCache
1111 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1112 && $this->exists()
1113 && empty( $oldid )
1114 && !$this->mTitle->isCssOrJsPage()
1115 && !$this->mTitle->isCssJsSubpage();
1116 }
1117
1118 /**
1119 * View redirect
1120 * @param $target Title object or Array of destination(s) to redirect
1121 * @param $appendSubtitle Boolean [optional]
1122 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1123 */
1124 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1125 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1126 # Display redirect
1127 if( !is_array( $target ) ) {
1128 $target = array( $target );
1129 }
1130 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1131 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1132 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1133 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1134
1135 if( $appendSubtitle ) {
1136 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1137 }
1138 $sk = $wgUser->getSkin();
1139 // the loop prepends the arrow image before the link, so the first case needs to be outside
1140 $title = array_shift( $target );
1141 if( $forceKnown ) {
1142 $link = $sk->link(
1143 $title,
1144 htmlspecialchars( $title->getFullText() ),
1145 array(),
1146 array(),
1147 array( 'known', 'noclasses' )
1148 );
1149 } else {
1150 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1151 }
1152 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1153 foreach( $target as $rt ) {
1154 if( $forceKnown ) {
1155 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1156 . $sk->link(
1157 $rt,
1158 htmlspecialchars( $rt->getFullText() ),
1159 array(),
1160 array(),
1161 array( 'known', 'noclasses' )
1162 );
1163 } else {
1164 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1165 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1166 }
1167 }
1168 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1169 '<span class="redirectText">'.$link.'</span>';
1170
1171 }
1172
1173 public function addTrackbacks() {
1174 global $wgOut, $wgUser;
1175 $dbr = wfGetDB( DB_SLAVE );
1176 $tbs = $dbr->select( 'trackbacks',
1177 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1178 array('tb_page' => $this->getID() )
1179 );
1180 if( !$dbr->numRows($tbs) ) return;
1181
1182 $tbtext = "";
1183 while( $o = $dbr->fetchObject($tbs) ) {
1184 $rmvtxt = "";
1185 if( $wgUser->isAllowed( 'trackback' ) ) {
1186 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1187 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1188 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1189 }
1190 $tbtext .= "\n";
1191 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1192 $o->tb_title,
1193 $o->tb_url,
1194 $o->tb_ex,
1195 $o->tb_name,
1196 $rmvtxt);
1197 }
1198 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1199 $this->mTitle->invalidateCache();
1200 }
1201
1202 public function deletetrackback() {
1203 global $wgUser, $wgRequest, $wgOut;
1204 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1205 $wgOut->addWikiMsg( 'sessionfailure' );
1206 return;
1207 }
1208
1209 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1210 if( count($permission_errors) ) {
1211 $wgOut->showPermissionsErrorPage( $permission_errors );
1212 return;
1213 }
1214
1215 $db = wfGetDB( DB_MASTER );
1216 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1217
1218 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1219 $this->mTitle->invalidateCache();
1220 }
1221
1222 public function render() {
1223 global $wgOut;
1224 $wgOut->setArticleBodyOnly(true);
1225 $this->view();
1226 }
1227
1228 /**
1229 * Handle action=purge
1230 */
1231 public function purge() {
1232 global $wgUser, $wgRequest, $wgOut;
1233 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1234 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1235 $this->doPurge();
1236 $this->view();
1237 }
1238 } else {
1239 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1240 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1241 $form = "<form method=\"post\" action=\"$action\">\n" .
1242 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1243 "</form>\n";
1244 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1245 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1246 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1247 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1248 $wgOut->addHTML( $top . $form . $bottom );
1249 }
1250 }
1251
1252 /**
1253 * Perform the actions of a page purging
1254 */
1255 public function doPurge() {
1256 global $wgUseSquid;
1257 // Invalidate the cache
1258 $this->mTitle->invalidateCache();
1259
1260 if( $wgUseSquid ) {
1261 // Commit the transaction before the purge is sent
1262 $dbw = wfGetDB( DB_MASTER );
1263 $dbw->immediateCommit();
1264
1265 // Send purge
1266 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1267 $update->doUpdate();
1268 }
1269 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1270 global $wgMessageCache;
1271 if( $this->getID() == 0 ) {
1272 $text = false;
1273 } else {
1274 $text = $this->getRawText();
1275 }
1276 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1277 }
1278 }
1279
1280 /**
1281 * Insert a new empty page record for this article.
1282 * This *must* be followed up by creating a revision
1283 * and running $this->updateToLatest( $rev_id );
1284 * or else the record will be left in a funky state.
1285 * Best if all done inside a transaction.
1286 *
1287 * @param $dbw Database
1288 * @return int The newly created page_id key, or false if the title already existed
1289 * @private
1290 */
1291 public function insertOn( $dbw ) {
1292 wfProfileIn( __METHOD__ );
1293
1294 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1295 $dbw->insert( 'page', array(
1296 'page_id' => $page_id,
1297 'page_namespace' => $this->mTitle->getNamespace(),
1298 'page_title' => $this->mTitle->getDBkey(),
1299 'page_counter' => 0,
1300 'page_restrictions' => '',
1301 'page_is_redirect' => 0, # Will set this shortly...
1302 'page_is_new' => 1,
1303 'page_random' => wfRandom(),
1304 'page_touched' => $dbw->timestamp(),
1305 'page_latest' => 0, # Fill this in shortly...
1306 'page_len' => 0, # Fill this in shortly...
1307 ), __METHOD__, 'IGNORE' );
1308
1309 $affected = $dbw->affectedRows();
1310 if( $affected ) {
1311 $newid = $dbw->insertId();
1312 $this->mTitle->resetArticleId( $newid );
1313 }
1314 wfProfileOut( __METHOD__ );
1315 return $affected ? $newid : false;
1316 }
1317
1318 /**
1319 * Update the page record to point to a newly saved revision.
1320 *
1321 * @param $dbw Database object
1322 * @param $revision Revision: For ID number, and text used to set
1323 length and redirect status fields
1324 * @param $lastRevision Integer: if given, will not overwrite the page field
1325 * when different from the currently set value.
1326 * Giving 0 indicates the new page flag should be set
1327 * on.
1328 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1329 * removing rows in redirect table.
1330 * @return bool true on success, false on failure
1331 * @private
1332 */
1333 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1334 wfProfileIn( __METHOD__ );
1335
1336 $text = $revision->getText();
1337 $rt = Title::newFromRedirect( $text );
1338
1339 $conditions = array( 'page_id' => $this->getId() );
1340 if( !is_null( $lastRevision ) ) {
1341 # An extra check against threads stepping on each other
1342 $conditions['page_latest'] = $lastRevision;
1343 }
1344
1345 $dbw->update( 'page',
1346 array( /* SET */
1347 'page_latest' => $revision->getId(),
1348 'page_touched' => $dbw->timestamp(),
1349 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1350 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1351 'page_len' => strlen( $text ),
1352 ),
1353 $conditions,
1354 __METHOD__ );
1355
1356 $result = $dbw->affectedRows() != 0;
1357 if( $result ) {
1358 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1359 }
1360
1361 wfProfileOut( __METHOD__ );
1362 return $result;
1363 }
1364
1365 /**
1366 * Add row to the redirect table if this is a redirect, remove otherwise.
1367 *
1368 * @param $dbw Database
1369 * @param $redirectTitle a title object pointing to the redirect target,
1370 * or NULL if this is not a redirect
1371 * @param $lastRevIsRedirect If given, will optimize adding and
1372 * removing rows in redirect table.
1373 * @return bool true on success, false on failure
1374 * @private
1375 */
1376 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1377 // Always update redirects (target link might have changed)
1378 // Update/Insert if we don't know if the last revision was a redirect or not
1379 // Delete if changing from redirect to non-redirect
1380 $isRedirect = !is_null($redirectTitle);
1381 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1382 wfProfileIn( __METHOD__ );
1383 if( $isRedirect ) {
1384 // This title is a redirect, Add/Update row in the redirect table
1385 $set = array( /* SET */
1386 'rd_namespace' => $redirectTitle->getNamespace(),
1387 'rd_title' => $redirectTitle->getDBkey(),
1388 'rd_from' => $this->getId(),
1389 );
1390 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1391 } else {
1392 // This is not a redirect, remove row from redirect table
1393 $where = array( 'rd_from' => $this->getId() );
1394 $dbw->delete( 'redirect', $where, __METHOD__);
1395 }
1396 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1397 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1398 }
1399 wfProfileOut( __METHOD__ );
1400 return ( $dbw->affectedRows() != 0 );
1401 }
1402 return true;
1403 }
1404
1405 /**
1406 * If the given revision is newer than the currently set page_latest,
1407 * update the page record. Otherwise, do nothing.
1408 *
1409 * @param $dbw Database object
1410 * @param $revision Revision object
1411 */
1412 public function updateIfNewerOn( &$dbw, $revision ) {
1413 wfProfileIn( __METHOD__ );
1414 $row = $dbw->selectRow(
1415 array( 'revision', 'page' ),
1416 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1417 array(
1418 'page_id' => $this->getId(),
1419 'page_latest=rev_id' ),
1420 __METHOD__ );
1421 if( $row ) {
1422 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1423 wfProfileOut( __METHOD__ );
1424 return false;
1425 }
1426 $prev = $row->rev_id;
1427 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1428 } else {
1429 # No or missing previous revision; mark the page as new
1430 $prev = 0;
1431 $lastRevIsRedirect = null;
1432 }
1433 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1434 wfProfileOut( __METHOD__ );
1435 return $ret;
1436 }
1437
1438 /**
1439 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1440 * @return string Complete article text, or null if error
1441 */
1442 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1443 wfProfileIn( __METHOD__ );
1444 if( strval( $section ) == '' ) {
1445 // Whole-page edit; let the whole text through
1446 } else {
1447 if( is_null($edittime) ) {
1448 $rev = Revision::newFromTitle( $this->mTitle );
1449 } else {
1450 $dbw = wfGetDB( DB_MASTER );
1451 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1452 }
1453 if( !$rev ) {
1454 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1455 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1456 return null;
1457 }
1458 $oldtext = $rev->getText();
1459
1460 if( $section == 'new' ) {
1461 # Inserting a new section
1462 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1463 $text = strlen( trim( $oldtext ) ) > 0
1464 ? "{$oldtext}\n\n{$subject}{$text}"
1465 : "{$subject}{$text}";
1466 } else {
1467 # Replacing an existing section; roll out the big guns
1468 global $wgParser;
1469 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1470 }
1471 }
1472 wfProfileOut( __METHOD__ );
1473 return $text;
1474 }
1475
1476 /**
1477 * This function is not deprecated until somebody fixes the core not to use
1478 * it. Nevertheless, use Article::doEdit() instead.
1479 */
1480 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1481 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1482 ( $isminor ? EDIT_MINOR : 0 ) |
1483 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1484 ( $bot ? EDIT_FORCE_BOT : 0 );
1485
1486 # If this is a comment, add the summary as headline
1487 if( $comment && $summary != "" ) {
1488 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1489 }
1490
1491 $this->doEdit( $text, $summary, $flags );
1492
1493 $dbw = wfGetDB( DB_MASTER );
1494 if($watchthis) {
1495 if(!$this->mTitle->userIsWatching()) {
1496 $dbw->begin();
1497 $this->doWatch();
1498 $dbw->commit();
1499 }
1500 } else {
1501 if( $this->mTitle->userIsWatching() ) {
1502 $dbw->begin();
1503 $this->doUnwatch();
1504 $dbw->commit();
1505 }
1506 }
1507 $this->doRedirect( $this->isRedirect( $text ) );
1508 }
1509
1510 /**
1511 * @deprecated use Article::doEdit()
1512 */
1513 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1514 wfDeprecated( __METHOD__ );
1515 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1516 ( $minor ? EDIT_MINOR : 0 ) |
1517 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1518
1519 $status = $this->doEdit( $text, $summary, $flags );
1520 if( !$status->isOK() ) {
1521 return false;
1522 }
1523
1524 $dbw = wfGetDB( DB_MASTER );
1525 if( $watchthis ) {
1526 if(!$this->mTitle->userIsWatching()) {
1527 $dbw->begin();
1528 $this->doWatch();
1529 $dbw->commit();
1530 }
1531 } else {
1532 if( $this->mTitle->userIsWatching() ) {
1533 $dbw->begin();
1534 $this->doUnwatch();
1535 $dbw->commit();
1536 }
1537 }
1538
1539 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1540 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1541
1542 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1543 return true;
1544 }
1545
1546 /**
1547 * Article::doEdit()
1548 *
1549 * Change an existing article or create a new article. Updates RC and all necessary caches,
1550 * optionally via the deferred update array.
1551 *
1552 * $wgUser must be set before calling this function.
1553 *
1554 * @param $text String: new text
1555 * @param $summary String: edit summary
1556 * @param $flags Integer bitfield:
1557 * EDIT_NEW
1558 * Article is known or assumed to be non-existent, create a new one
1559 * EDIT_UPDATE
1560 * Article is known or assumed to be pre-existing, update it
1561 * EDIT_MINOR
1562 * Mark this edit minor, if the user is allowed to do so
1563 * EDIT_SUPPRESS_RC
1564 * Do not log the change in recentchanges
1565 * EDIT_FORCE_BOT
1566 * Mark the edit a "bot" edit regardless of user rights
1567 * EDIT_DEFER_UPDATES
1568 * Defer some of the updates until the end of index.php
1569 * EDIT_AUTOSUMMARY
1570 * Fill in blank summaries with generated text where possible
1571 *
1572 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1573 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1574 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1575 * edit-already-exists error will be returned. These two conditions are also possible with
1576 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1577 *
1578 * @param $baseRevId the revision ID this edit was based off, if any
1579 * @param $user Optional user object, $wgUser will be used if not passed
1580 *
1581 * @return Status object. Possible errors:
1582 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1583 * edit-gone-missing: In update mode, but the article didn't exist
1584 * edit-conflict: In update mode, the article changed unexpectedly
1585 * edit-no-change: Warning that the text was the same as before
1586 * edit-already-exists: In creation mode, but the article already exists
1587 *
1588 * Extensions may define additional errors.
1589 *
1590 * $return->value will contain an associative array with members as follows:
1591 * new: Boolean indicating if the function attempted to create a new article
1592 * revision: The revision object for the inserted revision, or null
1593 *
1594 * Compatibility note: this function previously returned a boolean value indicating success/failure
1595 */
1596 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1597 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1598
1599 # Low-level sanity check
1600 if( $this->mTitle->getText() == '' ) {
1601 throw new MWException( 'Something is trying to edit an article with an empty title' );
1602 }
1603
1604 wfProfileIn( __METHOD__ );
1605
1606 $user = is_null($user) ? $wgUser : $user;
1607 $status = Status::newGood( array() );
1608
1609 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1610 $this->loadPageData();
1611
1612 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1613 $aid = $this->mTitle->getArticleID();
1614 if( $aid ) {
1615 $flags |= EDIT_UPDATE;
1616 } else {
1617 $flags |= EDIT_NEW;
1618 }
1619 }
1620
1621 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1622 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1623 {
1624 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1625 wfProfileOut( __METHOD__ );
1626 if( $status->isOK() ) {
1627 $status->fatal( 'edit-hook-aborted');
1628 }
1629 return $status;
1630 }
1631
1632 # Silently ignore EDIT_MINOR if not allowed
1633 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1634 $bot = $flags & EDIT_FORCE_BOT;
1635
1636 $oldtext = $this->getRawText(); // current revision
1637 $oldsize = strlen( $oldtext );
1638
1639 # Provide autosummaries if one is not provided and autosummaries are enabled.
1640 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1641 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1642 }
1643
1644 $editInfo = $this->prepareTextForEdit( $text );
1645 $text = $editInfo->pst;
1646 $newsize = strlen( $text );
1647
1648 $dbw = wfGetDB( DB_MASTER );
1649 $now = wfTimestampNow();
1650
1651 if( $flags & EDIT_UPDATE ) {
1652 # Update article, but only if changed.
1653 $status->value['new'] = false;
1654 # Make sure the revision is either completely inserted or not inserted at all
1655 if( !$wgDBtransactions ) {
1656 $userAbort = ignore_user_abort( true );
1657 }
1658
1659 $revisionId = 0;
1660
1661 $changed = ( strcmp( $text, $oldtext ) != 0 );
1662
1663 if( $changed ) {
1664 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1665 - (int)$this->isCountable( $oldtext );
1666 $this->mTotalAdjustment = 0;
1667
1668 if( !$this->mLatest ) {
1669 # Article gone missing
1670 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1671 $status->fatal( 'edit-gone-missing' );
1672 wfProfileOut( __METHOD__ );
1673 return $status;
1674 }
1675
1676 $revision = new Revision( array(
1677 'page' => $this->getId(),
1678 'comment' => $summary,
1679 'minor_edit' => $isminor,
1680 'text' => $text,
1681 'parent_id' => $this->mLatest,
1682 'user' => $user->getId(),
1683 'user_text' => $user->getName(),
1684 ) );
1685
1686 $dbw->begin();
1687 $revisionId = $revision->insertOn( $dbw );
1688
1689 # Update page
1690 #
1691 # Note that we use $this->mLatest instead of fetching a value from the master DB
1692 # during the course of this function. This makes sure that EditPage can detect
1693 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1694 # before this function is called. A previous function used a separate query, this
1695 # creates a window where concurrent edits can cause an ignored edit conflict.
1696 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1697
1698 if( !$ok ) {
1699 /* Belated edit conflict! Run away!! */
1700 $status->fatal( 'edit-conflict' );
1701 # Delete the invalid revision if the DB is not transactional
1702 if( !$wgDBtransactions ) {
1703 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1704 }
1705 $revisionId = 0;
1706 $dbw->rollback();
1707 } else {
1708 global $wgUseRCPatrol;
1709 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1710 # Update recentchanges
1711 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1712 # Mark as patrolled if the user can do so
1713 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1714 # Add RC row to the DB
1715 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1716 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1717 $revisionId, $patrolled
1718 );
1719 # Log auto-patrolled edits
1720 if( $patrolled ) {
1721 PatrolLog::record( $rc, true );
1722 }
1723 }
1724 $user->incEditCount();
1725 $dbw->commit();
1726 }
1727 } else {
1728 $status->warning( 'edit-no-change' );
1729 $revision = null;
1730 // Keep the same revision ID, but do some updates on it
1731 $revisionId = $this->getRevIdFetched();
1732 // Update page_touched, this is usually implicit in the page update
1733 // Other cache updates are done in onArticleEdit()
1734 $this->mTitle->invalidateCache();
1735 }
1736
1737 if( !$wgDBtransactions ) {
1738 ignore_user_abort( $userAbort );
1739 }
1740 // Now that ignore_user_abort is restored, we can respond to fatal errors
1741 if( !$status->isOK() ) {
1742 wfProfileOut( __METHOD__ );
1743 return $status;
1744 }
1745
1746 # Invalidate cache of this article and all pages using this article
1747 # as a template. Partly deferred.
1748 Article::onArticleEdit( $this->mTitle );
1749 # Update links tables, site stats, etc.
1750 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1751 } else {
1752 # Create new article
1753 $status->value['new'] = true;
1754
1755 # Set statistics members
1756 # We work out if it's countable after PST to avoid counter drift
1757 # when articles are created with {{subst:}}
1758 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1759 $this->mTotalAdjustment = 1;
1760
1761 $dbw->begin();
1762
1763 # Add the page record; stake our claim on this title!
1764 # This will return false if the article already exists
1765 $newid = $this->insertOn( $dbw );
1766
1767 if( $newid === false ) {
1768 $dbw->rollback();
1769 $status->fatal( 'edit-already-exists' );
1770 wfProfileOut( __METHOD__ );
1771 return $status;
1772 }
1773
1774 # Save the revision text...
1775 $revision = new Revision( array(
1776 'page' => $newid,
1777 'comment' => $summary,
1778 'minor_edit' => $isminor,
1779 'text' => $text,
1780 'user' => $user->getId(),
1781 'user_text' => $user->getName(),
1782 ) );
1783 $revisionId = $revision->insertOn( $dbw );
1784
1785 $this->mTitle->resetArticleID( $newid );
1786
1787 # Update the page record with revision data
1788 $this->updateRevisionOn( $dbw, $revision, 0 );
1789
1790 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1791 # Update recentchanges
1792 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1793 global $wgUseRCPatrol, $wgUseNPPatrol;
1794 # Mark as patrolled if the user can do so
1795 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
1796 # Add RC row to the DB
1797 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1798 '', strlen($text), $revisionId, $patrolled );
1799 # Log auto-patrolled edits
1800 if( $patrolled ) {
1801 PatrolLog::record( $rc, true );
1802 }
1803 }
1804 $user->incEditCount();
1805 $dbw->commit();
1806
1807 # Update links, etc.
1808 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1809
1810 # Clear caches
1811 Article::onArticleCreate( $this->mTitle );
1812
1813 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1814 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1815 }
1816
1817 # Do updates right now unless deferral was requested
1818 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
1819 wfDoUpdates();
1820 }
1821
1822 // Return the new revision (or null) to the caller
1823 $status->value['revision'] = $revision;
1824
1825 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1826 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1827
1828 wfProfileOut( __METHOD__ );
1829 return $status;
1830 }
1831
1832 /**
1833 * @deprecated wrapper for doRedirect
1834 */
1835 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1836 wfDeprecated( __METHOD__ );
1837 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1838 }
1839
1840 /**
1841 * Output a redirect back to the article.
1842 * This is typically used after an edit.
1843 *
1844 * @param $noRedir Boolean: add redirect=no
1845 * @param $sectionAnchor String: section to redirect to, including "#"
1846 * @param $extraQuery String: extra query params
1847 */
1848 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1849 global $wgOut;
1850 if( $noRedir ) {
1851 $query = 'redirect=no';
1852 if( $extraQuery )
1853 $query .= "&$query";
1854 } else {
1855 $query = $extraQuery;
1856 }
1857 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1858 }
1859
1860 /**
1861 * Mark this particular edit/page as patrolled
1862 */
1863 public function markpatrolled() {
1864 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1865 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1866
1867 # If we haven't been given an rc_id value, we can't do anything
1868 $rcid = (int) $wgRequest->getVal('rcid');
1869 $rc = RecentChange::newFromId($rcid);
1870 if( is_null($rc) ) {
1871 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1872 return;
1873 }
1874
1875 #It would be nice to see where the user had actually come from, but for now just guess
1876 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1877 $return = SpecialPage::getTitleFor( $returnto );
1878
1879 $dbw = wfGetDB( DB_MASTER );
1880 $errors = $rc->doMarkPatrolled();
1881
1882 if( in_array(array('rcpatroldisabled'), $errors) ) {
1883 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1884 return;
1885 }
1886
1887 if( in_array(array('hookaborted'), $errors) ) {
1888 // The hook itself has handled any output
1889 return;
1890 }
1891
1892 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1893 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1894 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1895 $wgOut->returnToMain( false, $return );
1896 return;
1897 }
1898
1899 if( !empty($errors) ) {
1900 $wgOut->showPermissionsErrorPage( $errors );
1901 return;
1902 }
1903
1904 # Inform the user
1905 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1906 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1907 $wgOut->returnToMain( false, $return );
1908 }
1909
1910 /**
1911 * User-interface handler for the "watch" action
1912 */
1913
1914 public function watch() {
1915 global $wgUser, $wgOut;
1916 if( $wgUser->isAnon() ) {
1917 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1918 return;
1919 }
1920 if( wfReadOnly() ) {
1921 $wgOut->readOnlyPage();
1922 return;
1923 }
1924 if( $this->doWatch() ) {
1925 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1926 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1927 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1928 }
1929 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1930 }
1931
1932 /**
1933 * Add this page to $wgUser's watchlist
1934 * @return bool true on successful watch operation
1935 */
1936 public function doWatch() {
1937 global $wgUser;
1938 if( $wgUser->isAnon() ) {
1939 return false;
1940 }
1941 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1942 $wgUser->addWatch( $this->mTitle );
1943 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1944 }
1945 return false;
1946 }
1947
1948 /**
1949 * User interface handler for the "unwatch" action.
1950 */
1951 public function unwatch() {
1952 global $wgUser, $wgOut;
1953 if( $wgUser->isAnon() ) {
1954 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1955 return;
1956 }
1957 if( wfReadOnly() ) {
1958 $wgOut->readOnlyPage();
1959 return;
1960 }
1961 if( $this->doUnwatch() ) {
1962 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1963 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1964 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1965 }
1966 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1967 }
1968
1969 /**
1970 * Stop watching a page
1971 * @return bool true on successful unwatch
1972 */
1973 public function doUnwatch() {
1974 global $wgUser;
1975 if( $wgUser->isAnon() ) {
1976 return false;
1977 }
1978 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1979 $wgUser->removeWatch( $this->mTitle );
1980 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1981 }
1982 return false;
1983 }
1984
1985 /**
1986 * action=protect handler
1987 */
1988 public function protect() {
1989 $form = new ProtectionForm( $this );
1990 $form->execute();
1991 }
1992
1993 /**
1994 * action=unprotect handler (alias)
1995 */
1996 public function unprotect() {
1997 $this->protect();
1998 }
1999
2000 /**
2001 * Update the article's restriction field, and leave a log entry.
2002 *
2003 * @param $limit Array: set of restriction keys
2004 * @param $reason String
2005 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2006 * @param $expiry Array: per restriction type expiration
2007 * @return bool true on success
2008 */
2009 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2010 global $wgUser, $wgRestrictionTypes, $wgContLang;
2011
2012 $id = $this->mTitle->getArticleID();
2013 if ( $id <= 0 ) {
2014 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2015 return false;
2016 }
2017
2018 if ( wfReadOnly() ) {
2019 wfDebug( "updateRestrictions failed: read-only\n" );
2020 return false;
2021 }
2022
2023 if ( !$this->mTitle->userCan( 'protect' ) ) {
2024 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2025 return false;
2026 }
2027
2028 if( !$cascade ) {
2029 $cascade = false;
2030 }
2031
2032 // Take this opportunity to purge out expired restrictions
2033 Title::purgeExpiredRestrictions();
2034
2035 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2036 # we expect a single selection, but the schema allows otherwise.
2037 $current = array();
2038 $updated = Article::flattenRestrictions( $limit );
2039 $changed = false;
2040 foreach( $wgRestrictionTypes as $action ) {
2041 if( isset( $expiry[$action] ) ) {
2042 # Get current restrictions on $action
2043 $aLimits = $this->mTitle->getRestrictions( $action );
2044 $current[$action] = implode( '', $aLimits );
2045 # Are any actual restrictions being dealt with here?
2046 $aRChanged = count($aLimits) || !empty($limit[$action]);
2047 # If something changed, we need to log it. Checking $aRChanged
2048 # assures that "unprotecting" a page that is not protected does
2049 # not log just because the expiry was "changed".
2050 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2051 $changed = true;
2052 }
2053 }
2054 }
2055
2056 $current = Article::flattenRestrictions( $current );
2057
2058 $changed = ($changed || $current != $updated );
2059 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
2060 $protect = ( $updated != '' );
2061
2062 # If nothing's changed, do nothing
2063 if( $changed ) {
2064 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2065
2066 $dbw = wfGetDB( DB_MASTER );
2067
2068 # Prepare a null revision to be added to the history
2069 $modified = $current != '' && $protect;
2070 if( $protect ) {
2071 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2072 } else {
2073 $comment_type = 'unprotectedarticle';
2074 }
2075 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2076
2077 # Only restrictions with the 'protect' right can cascade...
2078 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2079 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2080 # The schema allows multiple restrictions
2081 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2082 $cascade = false;
2083 $cascade_description = '';
2084 if( $cascade ) {
2085 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2086 }
2087
2088 if( $reason )
2089 $comment .= ": $reason";
2090
2091 $editComment = $comment;
2092 $encodedExpiry = array();
2093 $protect_description = '';
2094 foreach( $limit as $action => $restrictions ) {
2095 if ( !isset($expiry[$action]) )
2096 $expiry[$action] = 'infinite';
2097
2098 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
2099 if( $restrictions != '' ) {
2100 $protect_description .= "[$action=$restrictions] (";
2101 if( $encodedExpiry[$action] != 'infinity' ) {
2102 $protect_description .= wfMsgForContent( 'protect-expiring',
2103 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2104 $wgContLang->date( $expiry[$action], false, false ) ,
2105 $wgContLang->time( $expiry[$action], false, false ) );
2106 } else {
2107 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2108 }
2109 $protect_description .= ') ';
2110 }
2111 }
2112 $protect_description = trim($protect_description);
2113
2114 if( $protect_description && $protect )
2115 $editComment .= " ($protect_description)";
2116 if( $cascade )
2117 $editComment .= "$cascade_description";
2118 # Update restrictions table
2119 foreach( $limit as $action => $restrictions ) {
2120 if($restrictions != '' ) {
2121 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2122 array( 'pr_page' => $id,
2123 'pr_type' => $action,
2124 'pr_level' => $restrictions,
2125 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2126 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2127 } else {
2128 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2129 'pr_type' => $action ), __METHOD__ );
2130 }
2131 }
2132
2133 # Insert a null revision
2134 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2135 $nullRevId = $nullRevision->insertOn( $dbw );
2136
2137 $latest = $this->getLatest();
2138 # Update page record
2139 $dbw->update( 'page',
2140 array( /* SET */
2141 'page_touched' => $dbw->timestamp(),
2142 'page_restrictions' => '',
2143 'page_latest' => $nullRevId
2144 ), array( /* WHERE */
2145 'page_id' => $id
2146 ), 'Article::protect'
2147 );
2148
2149 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2150 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2151
2152 # Update the protection log
2153 $log = new LogPage( 'protect' );
2154 if( $protect ) {
2155 $params = array($protect_description,$cascade ? 'cascade' : '');
2156 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2157 } else {
2158 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2159 }
2160
2161 } # End hook
2162 } # End "changed" check
2163
2164 return true;
2165 }
2166
2167 /**
2168 * Take an array of page restrictions and flatten it to a string
2169 * suitable for insertion into the page_restrictions field.
2170 * @param $limit Array
2171 * @return String
2172 */
2173 protected static function flattenRestrictions( $limit ) {
2174 if( !is_array( $limit ) ) {
2175 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2176 }
2177 $bits = array();
2178 ksort( $limit );
2179 foreach( $limit as $action => $restrictions ) {
2180 if( $restrictions != '' ) {
2181 $bits[] = "$action=$restrictions";
2182 }
2183 }
2184 return implode( ':', $bits );
2185 }
2186
2187 /**
2188 * Auto-generates a deletion reason
2189 * @param &$hasHistory Boolean: whether the page has a history
2190 */
2191 public function generateReason( &$hasHistory ) {
2192 global $wgContLang;
2193 $dbw = wfGetDB( DB_MASTER );
2194 // Get the last revision
2195 $rev = Revision::newFromTitle( $this->mTitle );
2196 if( is_null( $rev ) )
2197 return false;
2198
2199 // Get the article's contents
2200 $contents = $rev->getText();
2201 $blank = false;
2202 // If the page is blank, use the text from the previous revision,
2203 // which can only be blank if there's a move/import/protect dummy revision involved
2204 if( $contents == '' ) {
2205 $prev = $rev->getPrevious();
2206 if( $prev ) {
2207 $contents = $prev->getText();
2208 $blank = true;
2209 }
2210 }
2211
2212 // Find out if there was only one contributor
2213 // Only scan the last 20 revisions
2214 $res = $dbw->select( 'revision', 'rev_user_text',
2215 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0' ),
2216 __METHOD__,
2217 array( 'LIMIT' => 20 )
2218 );
2219 if( $res === false )
2220 // This page has no revisions, which is very weird
2221 return false;
2222
2223 $hasHistory = ( $res->numRows() > 1 );
2224 $row = $dbw->fetchObject( $res );
2225 $onlyAuthor = $row->rev_user_text;
2226 // Try to find a second contributor
2227 foreach( $res as $row ) {
2228 if( $row->rev_user_text != $onlyAuthor ) {
2229 $onlyAuthor = false;
2230 break;
2231 }
2232 }
2233 $dbw->freeResult( $res );
2234
2235 // Generate the summary with a '$1' placeholder
2236 if( $blank ) {
2237 // The current revision is blank and the one before is also
2238 // blank. It's just not our lucky day
2239 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2240 } else {
2241 if( $onlyAuthor )
2242 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2243 else
2244 $reason = wfMsgForContent( 'excontent', '$1' );
2245 }
2246
2247 if( $reason == '-' ) {
2248 // Allow these UI messages to be blanked out cleanly
2249 return '';
2250 }
2251
2252 // Replace newlines with spaces to prevent uglyness
2253 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2254 // Calculate the maximum amount of chars to get
2255 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2256 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2257 $contents = $wgContLang->truncate( $contents, $maxLength );
2258 // Remove possible unfinished links
2259 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2260 // Now replace the '$1' placeholder
2261 $reason = str_replace( '$1', $contents, $reason );
2262 return $reason;
2263 }
2264
2265
2266 /*
2267 * UI entry point for page deletion
2268 */
2269 public function delete() {
2270 global $wgUser, $wgOut, $wgRequest;
2271
2272 $confirm = $wgRequest->wasPosted() &&
2273 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2274
2275 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2276 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2277
2278 $reason = $this->DeleteReasonList;
2279
2280 if( $reason != 'other' && $this->DeleteReason != '' ) {
2281 // Entry from drop down menu + additional comment
2282 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2283 } elseif( $reason == 'other' ) {
2284 $reason = $this->DeleteReason;
2285 }
2286 # Flag to hide all contents of the archived revisions
2287 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2288
2289 # This code desperately needs to be totally rewritten
2290
2291 # Read-only check...
2292 if( wfReadOnly() ) {
2293 $wgOut->readOnlyPage();
2294 return;
2295 }
2296
2297 # Check permissions
2298 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2299
2300 if( count( $permission_errors ) > 0 ) {
2301 $wgOut->showPermissionsErrorPage( $permission_errors );
2302 return;
2303 }
2304
2305 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2306
2307 # Better double-check that it hasn't been deleted yet!
2308 $dbw = wfGetDB( DB_MASTER );
2309 $conds = $this->mTitle->pageCond();
2310 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2311 if( $latest === false ) {
2312 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2313 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2314 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2315 return;
2316 }
2317
2318 # Hack for big sites
2319 $bigHistory = $this->isBigDeletion();
2320 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2321 global $wgLang, $wgDeleteRevisionsLimit;
2322 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2323 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2324 return;
2325 }
2326
2327 if( $confirm ) {
2328 $this->doDelete( $reason, $suppress );
2329 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2330 $this->doWatch();
2331 } elseif( $this->mTitle->userIsWatching() ) {
2332 $this->doUnwatch();
2333 }
2334 return;
2335 }
2336
2337 // Generate deletion reason
2338 $hasHistory = false;
2339 if( !$reason ) $reason = $this->generateReason($hasHistory);
2340
2341 // If the page has a history, insert a warning
2342 if( $hasHistory && !$confirm ) {
2343 $skin = $wgUser->getSkin();
2344 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2345 if( $bigHistory ) {
2346 global $wgLang, $wgDeleteRevisionsLimit;
2347 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2348 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2349 }
2350 }
2351
2352 return $this->confirmDelete( $reason );
2353 }
2354
2355 /**
2356 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2357 */
2358 public function isBigDeletion() {
2359 global $wgDeleteRevisionsLimit;
2360 if( $wgDeleteRevisionsLimit ) {
2361 $revCount = $this->estimateRevisionCount();
2362 return $revCount > $wgDeleteRevisionsLimit;
2363 }
2364 return false;
2365 }
2366
2367 /**
2368 * @return int approximate revision count
2369 */
2370 public function estimateRevisionCount() {
2371 $dbr = wfGetDB( DB_SLAVE );
2372 // For an exact count...
2373 //return $dbr->selectField( 'revision', 'COUNT(*)',
2374 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2375 return $dbr->estimateRowCount( 'revision', '*',
2376 array( 'rev_page' => $this->getId() ), __METHOD__ );
2377 }
2378
2379 /**
2380 * Get the last N authors
2381 * @param $num Integer: number of revisions to get
2382 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2383 * @return array Array of authors, duplicates not removed
2384 */
2385 public function getLastNAuthors( $num, $revLatest = 0 ) {
2386 wfProfileIn( __METHOD__ );
2387 // First try the slave
2388 // If that doesn't have the latest revision, try the master
2389 $continue = 2;
2390 $db = wfGetDB( DB_SLAVE );
2391 do {
2392 $res = $db->select( array( 'page', 'revision' ),
2393 array( 'rev_id', 'rev_user_text' ),
2394 array(
2395 'page_namespace' => $this->mTitle->getNamespace(),
2396 'page_title' => $this->mTitle->getDBkey(),
2397 'rev_page = page_id'
2398 ), __METHOD__, $this->getSelectOptions( array(
2399 'ORDER BY' => 'rev_timestamp DESC',
2400 'LIMIT' => $num
2401 ) )
2402 );
2403 if( !$res ) {
2404 wfProfileOut( __METHOD__ );
2405 return array();
2406 }
2407 $row = $db->fetchObject( $res );
2408 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2409 $db = wfGetDB( DB_MASTER );
2410 $continue--;
2411 } else {
2412 $continue = 0;
2413 }
2414 } while ( $continue );
2415
2416 $authors = array( $row->rev_user_text );
2417 while ( $row = $db->fetchObject( $res ) ) {
2418 $authors[] = $row->rev_user_text;
2419 }
2420 wfProfileOut( __METHOD__ );
2421 return $authors;
2422 }
2423
2424 /**
2425 * Output deletion confirmation dialog
2426 * @param $reason String: prefilled reason
2427 */
2428 public function confirmDelete( $reason ) {
2429 global $wgOut, $wgUser;
2430
2431 wfDebug( "Article::confirmDelete\n" );
2432
2433 $deleteBackLink = $wgUser->getSkin()->link(
2434 $this->mTitle,
2435 null,
2436 array(),
2437 array(),
2438 array( 'known', 'noclasses' )
2439 );
2440 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2441 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2442 $wgOut->addWikiMsg( 'confirmdeletetext' );
2443
2444 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2445 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2446 <td></td>
2447 <td class='mw-input'><strong>" .
2448 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2449 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2450 "</strong></td>
2451 </tr>";
2452 } else {
2453 $suppress = '';
2454 }
2455 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2456
2457 $form = Xml::openElement( 'form', array( 'method' => 'post',
2458 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2459 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2460 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2461 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2462 "<tr id=\"wpDeleteReasonListRow\">
2463 <td class='mw-label'>" .
2464 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2465 "</td>
2466 <td class='mw-input'>" .
2467 Xml::listDropDown( 'wpDeleteReasonList',
2468 wfMsgForContent( 'deletereason-dropdown' ),
2469 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2470 "</td>
2471 </tr>
2472 <tr id=\"wpDeleteReasonRow\">
2473 <td class='mw-label'>" .
2474 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2475 "</td>
2476 <td class='mw-input'>" .
2477 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2478 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2479 "</td>
2480 </tr>
2481 <tr>
2482 <td></td>
2483 <td class='mw-input'>" .
2484 Xml::checkLabel( wfMsg( 'watchthis' ),
2485 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2486 "</td>
2487 </tr>
2488 $suppress
2489 <tr>
2490 <td></td>
2491 <td class='mw-submit'>" .
2492 Xml::submitButton( wfMsg( 'deletepage' ),
2493 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2494 "</td>
2495 </tr>" .
2496 Xml::closeElement( 'table' ) .
2497 Xml::closeElement( 'fieldset' ) .
2498 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2499 Xml::closeElement( 'form' );
2500
2501 if( $wgUser->isAllowed( 'editinterface' ) ) {
2502 $skin = $wgUser->getSkin();
2503 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2504 $link = $skin->link(
2505 $title,
2506 wfMsgHtml( 'delete-edit-reasonlist' ),
2507 array(),
2508 array( 'action' => 'edit' )
2509 );
2510 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2511 }
2512
2513 $wgOut->addHTML( $form );
2514 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2515 }
2516
2517 /**
2518 * Perform a deletion and output success or failure messages
2519 */
2520 public function doDelete( $reason, $suppress = false ) {
2521 global $wgOut, $wgUser;
2522 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2523
2524 $error = '';
2525 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2526 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2527 $deleted = $this->mTitle->getPrefixedText();
2528
2529 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2530 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2531
2532 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2533
2534 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2535 $wgOut->returnToMain( false );
2536 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2537 } else {
2538 if( $error == '' ) {
2539 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2540 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2541 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2542 } else {
2543 $wgOut->showFatalError( $error );
2544 }
2545 }
2546 }
2547 }
2548
2549 /**
2550 * Back-end article deletion
2551 * Deletes the article with database consistency, writes logs, purges caches
2552 * Returns success
2553 */
2554 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2555 global $wgUseSquid, $wgDeferredUpdateList;
2556 global $wgUseTrackbacks;
2557
2558 wfDebug( __METHOD__."\n" );
2559
2560 $dbw = wfGetDB( DB_MASTER );
2561 $ns = $this->mTitle->getNamespace();
2562 $t = $this->mTitle->getDBkey();
2563 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2564
2565 if( $t == '' || $id == 0 ) {
2566 return false;
2567 }
2568
2569 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2570 array_push( $wgDeferredUpdateList, $u );
2571
2572 // Bitfields to further suppress the content
2573 if( $suppress ) {
2574 $bitfield = 0;
2575 // This should be 15...
2576 $bitfield |= Revision::DELETED_TEXT;
2577 $bitfield |= Revision::DELETED_COMMENT;
2578 $bitfield |= Revision::DELETED_USER;
2579 $bitfield |= Revision::DELETED_RESTRICTED;
2580 } else {
2581 $bitfield = 'rev_deleted';
2582 }
2583
2584 $dbw->begin();
2585 // For now, shunt the revision data into the archive table.
2586 // Text is *not* removed from the text table; bulk storage
2587 // is left intact to avoid breaking block-compression or
2588 // immutable storage schemes.
2589 //
2590 // For backwards compatibility, note that some older archive
2591 // table entries will have ar_text and ar_flags fields still.
2592 //
2593 // In the future, we may keep revisions and mark them with
2594 // the rev_deleted field, which is reserved for this purpose.
2595 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2596 array(
2597 'ar_namespace' => 'page_namespace',
2598 'ar_title' => 'page_title',
2599 'ar_comment' => 'rev_comment',
2600 'ar_user' => 'rev_user',
2601 'ar_user_text' => 'rev_user_text',
2602 'ar_timestamp' => 'rev_timestamp',
2603 'ar_minor_edit' => 'rev_minor_edit',
2604 'ar_rev_id' => 'rev_id',
2605 'ar_text_id' => 'rev_text_id',
2606 'ar_text' => '\'\'', // Be explicit to appease
2607 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2608 'ar_len' => 'rev_len',
2609 'ar_page_id' => 'page_id',
2610 'ar_deleted' => $bitfield
2611 ), array(
2612 'page_id' => $id,
2613 'page_id = rev_page'
2614 ), __METHOD__
2615 );
2616
2617 # Delete restrictions for it
2618 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2619
2620 # Now that it's safely backed up, delete it
2621 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2622 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2623 if( !$ok ) {
2624 $dbw->rollback();
2625 return false;
2626 }
2627
2628 # Fix category table counts
2629 $cats = array();
2630 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2631 foreach( $res as $row ) {
2632 $cats []= $row->cl_to;
2633 }
2634 $this->updateCategoryCounts( array(), $cats );
2635
2636 # If using cascading deletes, we can skip some explicit deletes
2637 if( !$dbw->cascadingDeletes() ) {
2638 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2639
2640 if($wgUseTrackbacks)
2641 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2642
2643 # Delete outgoing links
2644 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2645 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2646 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2647 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2648 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2649 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2650 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2651 }
2652
2653 # If using cleanup triggers, we can skip some manual deletes
2654 if( !$dbw->cleanupTriggers() ) {
2655 # Clean up recentchanges entries...
2656 $dbw->delete( 'recentchanges',
2657 array( 'rc_type != '.RC_LOG,
2658 'rc_namespace' => $this->mTitle->getNamespace(),
2659 'rc_title' => $this->mTitle->getDBkey() ),
2660 __METHOD__ );
2661 $dbw->delete( 'recentchanges',
2662 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2663 __METHOD__ );
2664 }
2665
2666 # Clear caches
2667 Article::onArticleDelete( $this->mTitle );
2668
2669 # Clear the cached article id so the interface doesn't act like we exist
2670 $this->mTitle->resetArticleID( 0 );
2671
2672 # Log the deletion, if the page was suppressed, log it at Oversight instead
2673 $logtype = $suppress ? 'suppress' : 'delete';
2674 $log = new LogPage( $logtype );
2675
2676 # Make sure logging got through
2677 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2678
2679 $dbw->commit();
2680
2681 return true;
2682 }
2683
2684 /**
2685 * Roll back the most recent consecutive set of edits to a page
2686 * from the same user; fails if there are no eligible edits to
2687 * roll back to, e.g. user is the sole contributor. This function
2688 * performs permissions checks on $wgUser, then calls commitRollback()
2689 * to do the dirty work
2690 *
2691 * @param $fromP String: Name of the user whose edits to rollback.
2692 * @param $summary String: Custom summary. Set to default summary if empty.
2693 * @param $token String: Rollback token.
2694 * @param $bot Boolean: If true, mark all reverted edits as bot.
2695 *
2696 * @param $resultDetails Array: contains result-specific array of additional values
2697 * 'alreadyrolled' : 'current' (rev)
2698 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2699 *
2700 * @return array of errors, each error formatted as
2701 * array(messagekey, param1, param2, ...).
2702 * On success, the array is empty. This array can also be passed to
2703 * OutputPage::showPermissionsErrorPage().
2704 */
2705 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2706 global $wgUser;
2707 $resultDetails = null;
2708
2709 # Check permissions
2710 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2711 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2712 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2713
2714 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2715 $errors[] = array( 'sessionfailure' );
2716
2717 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2718 $errors[] = array( 'actionthrottledtext' );
2719 }
2720 # If there were errors, bail out now
2721 if( !empty( $errors ) )
2722 return $errors;
2723
2724 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2725 }
2726
2727 /**
2728 * Backend implementation of doRollback(), please refer there for parameter
2729 * and return value documentation
2730 *
2731 * NOTE: This function does NOT check ANY permissions, it just commits the
2732 * rollback to the DB Therefore, you should only call this function direct-
2733 * ly if you want to use custom permissions checks. If you don't, use
2734 * doRollback() instead.
2735 */
2736 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2737 global $wgUseRCPatrol, $wgUser, $wgLang;
2738 $dbw = wfGetDB( DB_MASTER );
2739
2740 if( wfReadOnly() ) {
2741 return array( array( 'readonlytext' ) );
2742 }
2743
2744 # Get the last editor
2745 $current = Revision::newFromTitle( $this->mTitle );
2746 if( is_null( $current ) ) {
2747 # Something wrong... no page?
2748 return array(array('notanarticle'));
2749 }
2750
2751 $from = str_replace( '_', ' ', $fromP );
2752 if( $from != $current->getUserText() ) {
2753 $resultDetails = array( 'current' => $current );
2754 return array(array('alreadyrolled',
2755 htmlspecialchars($this->mTitle->getPrefixedText()),
2756 htmlspecialchars($fromP),
2757 htmlspecialchars($current->getUserText())
2758 ));
2759 }
2760
2761 # Get the last edit not by this guy
2762 $user = intval( $current->getUser() );
2763 $user_text = $dbw->addQuotes( $current->getUserText() );
2764 $s = $dbw->selectRow( 'revision',
2765 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2766 array( 'rev_page' => $current->getPage(),
2767 "rev_user != {$user} OR rev_user_text != {$user_text}"
2768 ), __METHOD__,
2769 array( 'USE INDEX' => 'page_timestamp',
2770 'ORDER BY' => 'rev_timestamp DESC' )
2771 );
2772 if( $s === false ) {
2773 # No one else ever edited this page
2774 return array(array('cantrollback'));
2775 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2776 # Only admins can see this text
2777 return array(array('notvisiblerev'));
2778 }
2779
2780 $set = array();
2781 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2782 # Mark all reverted edits as bot
2783 $set['rc_bot'] = 1;
2784 }
2785 if( $wgUseRCPatrol ) {
2786 # Mark all reverted edits as patrolled
2787 $set['rc_patrolled'] = 1;
2788 }
2789
2790 if( $set ) {
2791 $dbw->update( 'recentchanges', $set,
2792 array( /* WHERE */
2793 'rc_cur_id' => $current->getPage(),
2794 'rc_user_text' => $current->getUserText(),
2795 "rc_timestamp > '{$s->rev_timestamp}'",
2796 ), __METHOD__
2797 );
2798 }
2799
2800 # Generate the edit summary if necessary
2801 $target = Revision::newFromId( $s->rev_id );
2802 if( empty( $summary ) ){
2803 $summary = wfMsgForContent( 'revertpage' );
2804 }
2805
2806 # Allow the custom summary to use the same args as the default message
2807 $args = array(
2808 $target->getUserText(), $from, $s->rev_id,
2809 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2810 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2811 );
2812 $summary = wfMsgReplaceArgs( $summary, $args );
2813
2814 # Save
2815 $flags = EDIT_UPDATE;
2816
2817 if( $wgUser->isAllowed('minoredit') )
2818 $flags |= EDIT_MINOR;
2819
2820 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2821 $flags |= EDIT_FORCE_BOT;
2822 # Actually store the edit
2823 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2824 if( !empty( $status->value['revision'] ) ) {
2825 $revId = $status->value['revision']->getId();
2826 } else {
2827 $revId = false;
2828 }
2829
2830 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2831
2832 $resultDetails = array(
2833 'summary' => $summary,
2834 'current' => $current,
2835 'target' => $target,
2836 'newid' => $revId
2837 );
2838 return array();
2839 }
2840
2841 /**
2842 * User interface for rollback operations
2843 */
2844 public function rollback() {
2845 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2846 $details = null;
2847
2848 $result = $this->doRollback(
2849 $wgRequest->getVal( 'from' ),
2850 $wgRequest->getText( 'summary' ),
2851 $wgRequest->getVal( 'token' ),
2852 $wgRequest->getBool( 'bot' ),
2853 $details
2854 );
2855
2856 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2857 $wgOut->rateLimited();
2858 return;
2859 }
2860 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
2861 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2862 $errArray = $result[0];
2863 $errMsg = array_shift( $errArray );
2864 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2865 if( isset( $details['current'] ) ){
2866 $current = $details['current'];
2867 if( $current->getComment() != '' ) {
2868 $wgOut->addWikiMsgArray( 'editcomment', array(
2869 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2870 }
2871 }
2872 return;
2873 }
2874 # Display permissions errors before read-only message -- there's no
2875 # point in misleading the user into thinking the inability to rollback
2876 # is only temporary.
2877 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2878 # array_diff is completely broken for arrays of arrays, sigh. Re-
2879 # move any 'readonlytext' error manually.
2880 $out = array();
2881 foreach( $result as $error ) {
2882 if( $error != array( 'readonlytext' ) ) {
2883 $out []= $error;
2884 }
2885 }
2886 $wgOut->showPermissionsErrorPage( $out );
2887 return;
2888 }
2889 if( $result == array( array( 'readonlytext' ) ) ) {
2890 $wgOut->readOnlyPage();
2891 return;
2892 }
2893
2894 $current = $details['current'];
2895 $target = $details['target'];
2896 $newId = $details['newid'];
2897 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2898 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2899 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2900 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2901 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2902 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2903 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2904 $wgOut->returnToMain( false, $this->mTitle );
2905
2906 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2907 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
2908 $de->showDiff( '', '' );
2909 }
2910 }
2911
2912
2913 /**
2914 * Do standard deferred updates after page view
2915 */
2916 public function viewUpdates() {
2917 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2918 # Don't update page view counters on views from bot users (bug 14044)
2919 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2920 Article::incViewCount( $this->getID() );
2921 $u = new SiteStatsUpdate( 1, 0, 0 );
2922 array_push( $wgDeferredUpdateList, $u );
2923 }
2924 # Update newtalk / watchlist notification status
2925 $wgUser->clearNotification( $this->mTitle );
2926 }
2927
2928 /**
2929 * Prepare text which is about to be saved.
2930 * Returns a stdclass with source, pst and output members
2931 */
2932 public function prepareTextForEdit( $text, $revid=null ) {
2933 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2934 // Already prepared
2935 return $this->mPreparedEdit;
2936 }
2937 global $wgParser;
2938 $edit = (object)array();
2939 $edit->revid = $revid;
2940 $edit->newText = $text;
2941 $edit->pst = $this->preSaveTransform( $text );
2942 $options = new ParserOptions;
2943 $options->setTidy( true );
2944 $options->enableLimitReport();
2945 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2946 $edit->oldText = $this->getContent();
2947 $this->mPreparedEdit = $edit;
2948 return $edit;
2949 }
2950
2951 /**
2952 * Do standard deferred updates after page edit.
2953 * Update links tables, site stats, search index and message cache.
2954 * Purges pages that include this page if the text was changed here.
2955 * Every 100th edit, prune the recent changes table.
2956 *
2957 * @private
2958 * @param $text New text of the article
2959 * @param $summary Edit summary
2960 * @param $minoredit Minor edit
2961 * @param $timestamp_of_pagechange Timestamp associated with the page change
2962 * @param $newid rev_id value of the new revision
2963 * @param $changed Whether or not the content actually changed
2964 */
2965 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2966 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2967
2968 wfProfileIn( __METHOD__ );
2969
2970 # Parse the text
2971 # Be careful not to double-PST: $text is usually already PST-ed once
2972 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2973 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2974 $editInfo = $this->prepareTextForEdit( $text, $newid );
2975 } else {
2976 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2977 $editInfo = $this->mPreparedEdit;
2978 }
2979
2980 # Save it to the parser cache
2981 if( $wgEnableParserCache ) {
2982 $popts = new ParserOptions;
2983 $popts->setTidy( true );
2984 $popts->enableLimitReport();
2985 $parserCache = ParserCache::singleton();
2986 $parserCache->save( $editInfo->output, $this, $popts );
2987 }
2988
2989 # Update the links tables
2990 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2991 $u->doUpdate();
2992
2993 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2994
2995 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2996 if( 0 == mt_rand( 0, 99 ) ) {
2997 // Flush old entries from the `recentchanges` table; we do this on
2998 // random requests so as to avoid an increase in writes for no good reason
2999 global $wgRCMaxAge;
3000 $dbw = wfGetDB( DB_MASTER );
3001 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3002 $recentchanges = $dbw->tableName( 'recentchanges' );
3003 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3004 $dbw->query( $sql );
3005 }
3006 }
3007
3008 $id = $this->getID();
3009 $title = $this->mTitle->getPrefixedDBkey();
3010 $shortTitle = $this->mTitle->getDBkey();
3011
3012 if( 0 == $id ) {
3013 wfProfileOut( __METHOD__ );
3014 return;
3015 }
3016
3017 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3018 array_push( $wgDeferredUpdateList, $u );
3019 $u = new SearchUpdate( $id, $title, $text );
3020 array_push( $wgDeferredUpdateList, $u );
3021
3022 # If this is another user's talk page, update newtalk
3023 # Don't do this if $changed = false otherwise some idiot can null-edit a
3024 # load of user talk pages and piss people off, nor if it's a minor edit
3025 # by a properly-flagged bot.
3026 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3027 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3028 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3029 $other = User::newFromName( $shortTitle, false );
3030 if( !$other ) {
3031 wfDebug( __METHOD__.": invalid username\n" );
3032 } elseif( User::isIP( $shortTitle ) ) {
3033 // An anonymous user
3034 $other->setNewtalk( true );
3035 } elseif( $other->isLoggedIn() ) {
3036 $other->setNewtalk( true );
3037 } else {
3038 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3039 }
3040 }
3041 }
3042
3043 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3044 $wgMessageCache->replace( $shortTitle, $text );
3045 }
3046
3047 wfProfileOut( __METHOD__ );
3048 }
3049
3050 /**
3051 * Perform article updates on a special page creation.
3052 *
3053 * @param $rev Revision object
3054 *
3055 * @todo This is a shitty interface function. Kill it and replace the
3056 * other shitty functions like editUpdates and such so it's not needed
3057 * anymore.
3058 */
3059 public function createUpdates( $rev ) {
3060 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3061 $this->mTotalAdjustment = 1;
3062 $this->editUpdates( $rev->getText(), $rev->getComment(),
3063 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3064 }
3065
3066 /**
3067 * Generate the navigation links when browsing through an article revisions
3068 * It shows the information as:
3069 * Revision as of \<date\>; view current revision
3070 * \<- Previous version | Next Version -\>
3071 *
3072 * @param $oldid String: revision ID of this article revision
3073 */
3074 public function setOldSubtitle( $oldid = 0 ) {
3075 global $wgLang, $wgOut, $wgUser, $wgRequest;
3076
3077 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3078 return;
3079 }
3080
3081 $revision = Revision::newFromId( $oldid );
3082
3083 $current = ( $oldid == $this->mLatest );
3084 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3085 $tddate = $wgLang->time( $this->mTimestamp, true );
3086 $tdtime = $wgLang->time( $this->mTimestamp, true );
3087 $sk = $wgUser->getSkin();
3088 $lnk = $current
3089 ? wfMsgHtml( 'currentrevisionlink' )
3090 : $sk->link(
3091 $this->mTitle,
3092 wfMsgHtml( 'currentrevisionlink' ),
3093 array(),
3094 array(),
3095 array( 'known', 'noclasses' )
3096 );
3097 $curdiff = $current
3098 ? wfMsgHtml( 'diff' )
3099 : $sk->link(
3100 $this->mTitle,
3101 wfMsgHtml( 'diff' ),
3102 array(),
3103 array(
3104 'diff' => 'cur',
3105 'oldid' => $oldid
3106 ),
3107 array( 'known', 'noclasses' )
3108 );
3109 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3110 $prevlink = $prev
3111 ? $sk->link(
3112 $this->mTitle,
3113 wfMsgHtml( 'previousrevision' ),
3114 array(),
3115 array(
3116 'direction' => 'prev',
3117 'oldid' => $oldid
3118 ),
3119 array( 'known', 'noclasses' )
3120 )
3121 : wfMsgHtml( 'previousrevision' );
3122 $prevdiff = $prev
3123 ? $sk->link(
3124 $this->mTitle,
3125 wfMsgHtml( 'diff' ),
3126 array(),
3127 array(
3128 'diff' => 'prev',
3129 'oldid' => $oldid
3130 ),
3131 array( 'known', 'noclasses' )
3132 )
3133 : wfMsgHtml( 'diff' );
3134 $nextlink = $current
3135 ? wfMsgHtml( 'nextrevision' )
3136 : $sk->link(
3137 $this->mTitle,
3138 wfMsgHtml( 'nextrevision' ),
3139 array(),
3140 array(
3141 'direction' => 'next',
3142 'oldid' => $oldid
3143 ),
3144 array( 'known', 'noclasses' )
3145 );
3146 $nextdiff = $current
3147 ? wfMsgHtml( 'diff' )
3148 : $sk->link(
3149 $this->mTitle,
3150 wfMsgHtml( 'diff' ),
3151 array(),
3152 array(
3153 'diff' => 'next',
3154 'oldid' => $oldid
3155 ),
3156 array( 'known', 'noclasses' )
3157 );
3158
3159 $cdel='';
3160 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3161 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
3162 if( $revision->isCurrent() ) {
3163 // We don't handle top deleted edits too well
3164 $cdel = wfMsgHtml( 'rev-delundel' );
3165 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3166 // If revision was hidden from sysops
3167 $cdel = wfMsgHtml( 'rev-delundel' );
3168 } else {
3169 $cdel = $sk->link(
3170 $revdel,
3171 wfMsgHtml('rev-delundel'),
3172 array(),
3173 array(
3174 'type' => 'revision',
3175 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3176 'ids' => urlencode( $oldid )
3177 ),
3178 array( 'known', 'noclasses' )
3179 );
3180 // Bolden oversighted content
3181 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3182 $cdel = "<strong>$cdel</strong>";
3183 }
3184 $cdel = "(<small>$cdel</small>) ";
3185 }
3186 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3187 # Show user links if allowed to see them. If hidden, then show them only if requested...
3188 $userlinks = $sk->revUserTools( $revision, !$unhide );
3189
3190 $m = wfMsg( 'revision-info-current' );
3191 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3192 ? 'revision-info-current'
3193 : 'revision-info';
3194
3195 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3196 wfMsgExt(
3197 $infomsg,
3198 array( 'parseinline', 'replaceafter' ),
3199 $td,
3200 $userlinks,
3201 $revision->getID(),
3202 $tddate,
3203 $tdtime
3204 ) .
3205 "</div>\n" .
3206 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3207 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3208 $wgOut->setSubtitle( $r );
3209 }
3210
3211 /**
3212 * This function is called right before saving the wikitext,
3213 * so we can do things like signatures and links-in-context.
3214 *
3215 * @param $text String
3216 */
3217 public function preSaveTransform( $text ) {
3218 global $wgParser, $wgUser;
3219 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3220 }
3221
3222 /* Caching functions */
3223
3224 /**
3225 * checkLastModified returns true if it has taken care of all
3226 * output to the client that is necessary for this request.
3227 * (that is, it has sent a cached version of the page)
3228 */
3229 protected function tryFileCache() {
3230 static $called = false;
3231 if( $called ) {
3232 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3233 return false;
3234 }
3235 $called = true;
3236 if( $this->isFileCacheable() ) {
3237 $cache = new HTMLFileCache( $this->mTitle );
3238 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3239 wfDebug( "Article::tryFileCache(): about to load file\n" );
3240 $cache->loadFromFileCache();
3241 return true;
3242 } else {
3243 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3244 ob_start( array(&$cache, 'saveToFileCache' ) );
3245 }
3246 } else {
3247 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3248 }
3249 return false;
3250 }
3251
3252 /**
3253 * Check if the page can be cached
3254 * @return bool
3255 */
3256 public function isFileCacheable() {
3257 $cacheable = false;
3258 if( HTMLFileCache::useFileCache() ) {
3259 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3260 // Extension may have reason to disable file caching on some pages.
3261 if( $cacheable ) {
3262 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3263 }
3264 }
3265 return $cacheable;
3266 }
3267
3268 /**
3269 * Loads page_touched and returns a value indicating if it should be used
3270 *
3271 */
3272 public function checkTouched() {
3273 if( !$this->mDataLoaded ) {
3274 $this->loadPageData();
3275 }
3276 return !$this->mIsRedirect;
3277 }
3278
3279 /**
3280 * Get the page_touched field
3281 */
3282 public function getTouched() {
3283 # Ensure that page data has been loaded
3284 if( !$this->mDataLoaded ) {
3285 $this->loadPageData();
3286 }
3287 return $this->mTouched;
3288 }
3289
3290 /**
3291 * Get the page_latest field
3292 */
3293 public function getLatest() {
3294 if( !$this->mDataLoaded ) {
3295 $this->loadPageData();
3296 }
3297 return (int)$this->mLatest;
3298 }
3299
3300 /**
3301 * Edit an article without doing all that other stuff
3302 * The article must already exist; link tables etc
3303 * are not updated, caches are not flushed.
3304 *
3305 * @param $text String: text submitted
3306 * @param $comment String: comment submitted
3307 * @param $minor Boolean: whereas it's a minor modification
3308 */
3309 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3310 wfProfileIn( __METHOD__ );
3311
3312 $dbw = wfGetDB( DB_MASTER );
3313 $revision = new Revision( array(
3314 'page' => $this->getId(),
3315 'text' => $text,
3316 'comment' => $comment,
3317 'minor_edit' => $minor ? 1 : 0,
3318 ) );
3319 $revision->insertOn( $dbw );
3320 $this->updateRevisionOn( $dbw, $revision );
3321
3322 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3323
3324 wfProfileOut( __METHOD__ );
3325 }
3326
3327 /**
3328 * Used to increment the view counter
3329 *
3330 * @param $id Integer: article id
3331 */
3332 public static function incViewCount( $id ) {
3333 $id = intval( $id );
3334 global $wgHitcounterUpdateFreq, $wgDBtype;
3335
3336 $dbw = wfGetDB( DB_MASTER );
3337 $pageTable = $dbw->tableName( 'page' );
3338 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3339 $acchitsTable = $dbw->tableName( 'acchits' );
3340
3341 if( $wgHitcounterUpdateFreq <= 1 ) {
3342 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3343 return;
3344 }
3345
3346 # Not important enough to warrant an error page in case of failure
3347 $oldignore = $dbw->ignoreErrors( true );
3348
3349 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3350
3351 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3352 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3353 # Most of the time (or on SQL errors), skip row count check
3354 $dbw->ignoreErrors( $oldignore );
3355 return;
3356 }
3357
3358 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3359 $row = $dbw->fetchObject( $res );
3360 $rown = intval( $row->n );
3361 if( $rown >= $wgHitcounterUpdateFreq ){
3362 wfProfileIn( 'Article::incViewCount-collect' );
3363 $old_user_abort = ignore_user_abort( true );
3364
3365 if($wgDBtype == 'mysql')
3366 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3367 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3368 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3369 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3370 'GROUP BY hc_id');
3371 $dbw->query("DELETE FROM $hitcounterTable");
3372 if($wgDBtype == 'mysql') {
3373 $dbw->query('UNLOCK TABLES');
3374 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3375 'WHERE page_id = hc_id');
3376 }
3377 else {
3378 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3379 "FROM $acchitsTable WHERE page_id = hc_id");
3380 }
3381 $dbw->query("DROP TABLE $acchitsTable");
3382
3383 ignore_user_abort( $old_user_abort );
3384 wfProfileOut( 'Article::incViewCount-collect' );
3385 }
3386 $dbw->ignoreErrors( $oldignore );
3387 }
3388
3389 /**#@+
3390 * The onArticle*() functions are supposed to be a kind of hooks
3391 * which should be called whenever any of the specified actions
3392 * are done.
3393 *
3394 * This is a good place to put code to clear caches, for instance.
3395 *
3396 * This is called on page move and undelete, as well as edit
3397 *
3398 * @param $title a title object
3399 */
3400
3401 public static function onArticleCreate( $title ) {
3402 # Update existence markers on article/talk tabs...
3403 if( $title->isTalkPage() ) {
3404 $other = $title->getSubjectPage();
3405 } else {
3406 $other = $title->getTalkPage();
3407 }
3408 $other->invalidateCache();
3409 $other->purgeSquid();
3410
3411 $title->touchLinks();
3412 $title->purgeSquid();
3413 $title->deleteTitleProtection();
3414 }
3415
3416 public static function onArticleDelete( $title ) {
3417 global $wgMessageCache;
3418 # Update existence markers on article/talk tabs...
3419 if( $title->isTalkPage() ) {
3420 $other = $title->getSubjectPage();
3421 } else {
3422 $other = $title->getTalkPage();
3423 }
3424 $other->invalidateCache();
3425 $other->purgeSquid();
3426
3427 $title->touchLinks();
3428 $title->purgeSquid();
3429
3430 # File cache
3431 HTMLFileCache::clearFileCache( $title );
3432
3433 # Messages
3434 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3435 $wgMessageCache->replace( $title->getDBkey(), false );
3436 }
3437 # Images
3438 if( $title->getNamespace() == NS_FILE ) {
3439 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3440 $update->doUpdate();
3441 }
3442 # User talk pages
3443 if( $title->getNamespace() == NS_USER_TALK ) {
3444 $user = User::newFromName( $title->getText(), false );
3445 $user->setNewtalk( false );
3446 }
3447 # Image redirects
3448 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3449 }
3450
3451 /**
3452 * Purge caches on page update etc
3453 */
3454 public static function onArticleEdit( $title, $flags = '' ) {
3455 global $wgDeferredUpdateList;
3456
3457 // Invalidate caches of articles which include this page
3458 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3459
3460 // Invalidate the caches of all pages which redirect here
3461 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3462
3463 # Purge squid for this page only
3464 $title->purgeSquid();
3465
3466 # Clear file cache for this page only
3467 HTMLFileCache::clearFileCache( $title );
3468 }
3469
3470 /**#@-*/
3471
3472 /**
3473 * Overriden by ImagePage class, only present here to avoid a fatal error
3474 * Called for ?action=revert
3475 */
3476 public function revert() {
3477 global $wgOut;
3478 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3479 }
3480
3481 /**
3482 * Info about this page
3483 * Called for ?action=info when $wgAllowPageInfo is on.
3484 */
3485 public function info() {
3486 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3487
3488 if( !$wgAllowPageInfo ) {
3489 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3490 return;
3491 }
3492
3493 $page = $this->mTitle->getSubjectPage();
3494
3495 $wgOut->setPagetitle( $page->getPrefixedText() );
3496 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3497 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3498
3499 if( !$this->mTitle->exists() ) {
3500 $wgOut->addHTML( '<div class="noarticletext">' );
3501 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3502 // This doesn't quite make sense; the user is asking for
3503 // information about the _page_, not the message... -- RC
3504 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3505 } else {
3506 $msg = $wgUser->isLoggedIn()
3507 ? 'noarticletext'
3508 : 'noarticletextanon';
3509 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3510 }
3511 $wgOut->addHTML( '</div>' );
3512 } else {
3513 $dbr = wfGetDB( DB_SLAVE );
3514 $wl_clause = array(
3515 'wl_title' => $page->getDBkey(),
3516 'wl_namespace' => $page->getNamespace() );
3517 $numwatchers = $dbr->selectField(
3518 'watchlist',
3519 'COUNT(*)',
3520 $wl_clause,
3521 __METHOD__,
3522 $this->getSelectOptions() );
3523
3524 $pageInfo = $this->pageCountInfo( $page );
3525 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3526
3527 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3528 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3529 if( $talkInfo ) {
3530 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3531 }
3532 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3533 if( $talkInfo ) {
3534 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3535 }
3536 $wgOut->addHTML( '</ul>' );
3537 }
3538 }
3539
3540 /**
3541 * Return the total number of edits and number of unique editors
3542 * on a given page. If page does not exist, returns false.
3543 *
3544 * @param $title Title object
3545 * @return array
3546 */
3547 public function pageCountInfo( $title ) {
3548 $id = $title->getArticleId();
3549 if( $id == 0 ) {
3550 return false;
3551 }
3552 $dbr = wfGetDB( DB_SLAVE );
3553 $rev_clause = array( 'rev_page' => $id );
3554 $edits = $dbr->selectField(
3555 'revision',
3556 'COUNT(rev_page)',
3557 $rev_clause,
3558 __METHOD__,
3559 $this->getSelectOptions()
3560 );
3561 $authors = $dbr->selectField(
3562 'revision',
3563 'COUNT(DISTINCT rev_user_text)',
3564 $rev_clause,
3565 __METHOD__,
3566 $this->getSelectOptions()
3567 );
3568 return array( 'edits' => $edits, 'authors' => $authors );
3569 }
3570
3571 /**
3572 * Return a list of templates used by this article.
3573 * Uses the templatelinks table
3574 *
3575 * @return Array of Title objects
3576 */
3577 public function getUsedTemplates() {
3578 $result = array();
3579 $id = $this->mTitle->getArticleID();
3580 if( $id == 0 ) {
3581 return array();
3582 }
3583 $dbr = wfGetDB( DB_SLAVE );
3584 $res = $dbr->select( array( 'templatelinks' ),
3585 array( 'tl_namespace', 'tl_title' ),
3586 array( 'tl_from' => $id ),
3587 __METHOD__ );
3588 if( $res !== false ) {
3589 foreach( $res as $row ) {
3590 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3591 }
3592 }
3593 $dbr->freeResult( $res );
3594 return $result;
3595 }
3596
3597 /**
3598 * Returns a list of hidden categories this page is a member of.
3599 * Uses the page_props and categorylinks tables.
3600 *
3601 * @return Array of Title objects
3602 */
3603 public function getHiddenCategories() {
3604 $result = array();
3605 $id = $this->mTitle->getArticleID();
3606 if( $id == 0 ) {
3607 return array();
3608 }
3609 $dbr = wfGetDB( DB_SLAVE );
3610 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3611 array( 'cl_to' ),
3612 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3613 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3614 __METHOD__ );
3615 if( $res !== false ) {
3616 foreach( $res as $row ) {
3617 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3618 }
3619 }
3620 $dbr->freeResult( $res );
3621 return $result;
3622 }
3623
3624 /**
3625 * Return an applicable autosummary if one exists for the given edit.
3626 * @param $oldtext String: the previous text of the page.
3627 * @param $newtext String: The submitted text of the page.
3628 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3629 * @return string An appropriate autosummary, or an empty string.
3630 */
3631 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3632 # Decide what kind of autosummary is needed.
3633
3634 # Redirect autosummaries
3635 $ot = Title::newFromRedirect( $oldtext );
3636 $rt = Title::newFromRedirect( $newtext );
3637 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3638 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3639 }
3640
3641 # New page autosummaries
3642 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3643 # If they're making a new article, give its text, truncated, in the summary.
3644 global $wgContLang;
3645 $truncatedtext = $wgContLang->truncate(
3646 str_replace("\n", ' ', $newtext),
3647 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3648 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3649 }
3650
3651 # Blanking autosummaries
3652 if( $oldtext != '' && $newtext == '' ) {
3653 return wfMsgForContent( 'autosumm-blank' );
3654 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3655 # Removing more than 90% of the article
3656 global $wgContLang;
3657 $truncatedtext = $wgContLang->truncate(
3658 $newtext,
3659 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3660 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3661 }
3662
3663 # If we reach this point, there's no applicable autosummary for our case, so our
3664 # autosummary is empty.
3665 return '';
3666 }
3667
3668 /**
3669 * Add the primary page-view wikitext to the output buffer
3670 * Saves the text into the parser cache if possible.
3671 * Updates templatelinks if it is out of date.
3672 *
3673 * @param $text String
3674 * @param $cache Boolean
3675 */
3676 public function outputWikiText( $text, $cache = true ) {
3677 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3678
3679 $popts = $wgOut->parserOptions();
3680 $popts->setTidy(true);
3681 $popts->enableLimitReport();
3682 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3683 $popts, true, true, $this->getRevIdFetched() );
3684 $popts->setTidy(false);
3685 $popts->enableLimitReport( false );
3686 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3687 $parserCache = ParserCache::singleton();
3688 $parserCache->save( $parserOutput, $this, $popts );
3689 }
3690 // Make sure file cache is not used on uncacheable content.
3691 // Output that has magic words in it can still use the parser cache
3692 // (if enabled), though it will generally expire sooner.
3693 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3694 $wgUseFileCache = false;
3695 }
3696
3697 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3698 // templatelinks table may have become out of sync,
3699 // especially if using variable-based transclusions.
3700 // For paranoia, check if things have changed and if
3701 // so apply updates to the database. This will ensure
3702 // that cascaded protections apply as soon as the changes
3703 // are visible.
3704
3705 # Get templates from templatelinks
3706 $id = $this->mTitle->getArticleID();
3707
3708 $tlTemplates = array();
3709
3710 $dbr = wfGetDB( DB_SLAVE );
3711 $res = $dbr->select( array( 'templatelinks' ),
3712 array( 'tl_namespace', 'tl_title' ),
3713 array( 'tl_from' => $id ),
3714 __METHOD__ );
3715
3716 global $wgContLang;
3717 foreach( $res as $row ) {
3718 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3719 }
3720
3721 # Get templates from parser output.
3722 $poTemplates = array();
3723 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3724 foreach ( $templates as $dbk => $id ) {
3725 $poTemplates["$ns:$dbk"] = true;
3726 }
3727 }
3728
3729 # Get the diff
3730 # Note that we simulate array_diff_key in PHP <5.0.x
3731 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3732
3733 if( count( $templates_diff ) > 0 ) {
3734 # Whee, link updates time.
3735 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3736 $u->doUpdate();
3737 }
3738 }
3739
3740 $wgOut->addParserOutput( $parserOutput );
3741 }
3742
3743 /**
3744 * Update all the appropriate counts in the category table, given that
3745 * we've added the categories $added and deleted the categories $deleted.
3746 *
3747 * @param $added array The names of categories that were added
3748 * @param $deleted array The names of categories that were deleted
3749 * @return null
3750 */
3751 public function updateCategoryCounts( $added, $deleted ) {
3752 $ns = $this->mTitle->getNamespace();
3753 $dbw = wfGetDB( DB_MASTER );
3754
3755 # First make sure the rows exist. If one of the "deleted" ones didn't
3756 # exist, we might legitimately not create it, but it's simpler to just
3757 # create it and then give it a negative value, since the value is bogus
3758 # anyway.
3759 #
3760 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3761 $insertCats = array_merge( $added, $deleted );
3762 if( !$insertCats ) {
3763 # Okay, nothing to do
3764 return;
3765 }
3766 $insertRows = array();
3767 foreach( $insertCats as $cat ) {
3768 $insertRows[] = array( 'cat_title' => $cat );
3769 }
3770 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3771
3772 $addFields = array( 'cat_pages = cat_pages + 1' );
3773 $removeFields = array( 'cat_pages = cat_pages - 1' );
3774 if( $ns == NS_CATEGORY ) {
3775 $addFields[] = 'cat_subcats = cat_subcats + 1';
3776 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3777 } elseif( $ns == NS_FILE ) {
3778 $addFields[] = 'cat_files = cat_files + 1';
3779 $removeFields[] = 'cat_files = cat_files - 1';
3780 }
3781
3782 if( $added ) {
3783 $dbw->update(
3784 'category',
3785 $addFields,
3786 array( 'cat_title' => $added ),
3787 __METHOD__
3788 );
3789 }
3790 if( $deleted ) {
3791 $dbw->update(
3792 'category',
3793 $removeFields,
3794 array( 'cat_title' => $deleted ),
3795 __METHOD__
3796 );
3797 }
3798 }
3799 }